Search code examples
javascriptvue.jsjavascript-objectsvue-i18n

JavaScript Nested Objects Reformatting for i18n-vue


I have a JS Object like this shown in the first example, in a VUE JS web application utilizing i18n-vue. My translations are stored in the database and are in the format below when I retrieve them.

I need to reformat it to work with i18n-vue, but I am having no luck getting it working.

I need to go from this:

{
 0:{
     directory: {
       0: { english: 'Home', value: 'Casa' }
       1: { english: 'News', value: 'Noticias' }
       2: { english: 'Contact', value: 'Contacto' }
     }
     locale: 'es'
   }
 1:{
     directory: {
       0: { english: 'Home', value: '家' }
       1: { english: 'News', value: '消息' }
       2: { english: 'Contact', value: '接触' }
     }
     locale: 'zh'
   }
}

To this:

{
 'es': {
   'Home': 'Casa',
   'News': 'Noticias',
   'Contact': 'Contacto',
  },
 'zh': {
   'Home': '家',
   'News': '消息',
   'Contact': '接触',
  },
}

Any help would be very much appreciated. I'm still learning JS and have been able to solve most issues reading SO but this one really has me confused. Thanks in advance!


Solution

  • I assumed your input is an object, using .reduce() can transform the object to another look.

    You can run the snippet to see the result

    const translations = {
     0:{
         directory: {
           0: { english: 'Home', value: 'Casa' },
           1: { english: 'News', value: 'Noticias' },
           2: { english: 'Contact', value: 'Contacto' }
         },
         locale: 'es'
     },
     1:{
         directory: {
           0: { english: 'Home', value: '家' },
           1: { english: 'News', value: '消息' },
           2: { english: 'Contact', value: '接触' }
         },
         locale: 'zh'
       }
    }
    
    /* transformation */
    const result = Object.keys(translations).reduce((translationObj, key) => {
      const { directory, locale } = translations[key]
    
      // transform directory to be { 'Home': 'Casa' }
      const directories = Object.keys(directory).reduce((directoryObj, directoryKey) => {
         const { english, value } = directory[directoryKey]
         return ({ ...directoryObj, [english]: value })
      }, {})
    
      
      return ({ ...translationObj, [locale]: directories })
    }, {})
    
    console.log(result)