Transforming Nested JavaScript Objects for Internationalization in Vue

In my VUE JS web application that utilizes i18n-vue, I am facing an issue with reformatting a JS Object to work with the i18n-vue setup. The translations are retrieved from the database and are structured in a certain way as shown below.

I have tried several approaches but so far have not been successful in getting it to work properly.

The initial format looks like 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'
   }
}

The desired format should be like this:

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

Any assistance on how to achieve this would be highly appreciated. While I am still learning JavaScript and have managed to solve many problems by reading resources like Stack Overflow, this particular issue has me stumped. Thank you in advance for your help!

Answer №1

Assuming that the input provided is in object form, utilizing the .reduce() method can serve as a means to modify the object into a different structure.

Feel free to execute the code snippet below to observe the outcome:

const data = {
 0:{
     info: {
       0: { name: 'John', age: 30 },
       1: { name: 'Sarah', age: 25 },
       2: { name: 'Tom', age: 35 }
     },
     group: 'A'
 },
 1:{
     info: {
       0: { name: 'Alice', age: 28 },
       1: { name: 'Bob', age: 32 },
       2: { name: 'Eve', age: 27 }
     },
     group: 'B'
   }
}

/* Transformation process */
const modifiedData = Object.keys(data).reduce((modifiedObj, key) => {
  const { info, group } = data[key]

  // Modify information to show { 'John': 30 }
  const updatedInfo = Object.keys(info).reduce((infoObj, infoKey) => {
     const { name, age } = info[infoKey]
     return ({ ...infoObj, [name]: age })
  }, {})

  
  return ({ ...modifiedObj, [group]: updatedInfo })
}, {})

console.log(modifiedData)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After compiling my project using npm run dev, Vue 3 throws an error

Hey there! I recently attempted to install the necessary dependencies for a Vue.JS app repository by running npm install. Subsequently, I launched the Vue.JS app using npm run dev. However, upon execution, an error popped up in the terminal: PS G:\ma ...

Angular HttpClient does not support cross-domain POST requests, unlike jQuery which does

I am transitioning to Angular 13 and I want to switch from using jQuery.ajax to HttpClient. The jquery code below is currently functional: function asyncAjax(url: any){ return new Promise(function(resolve, reject) { $.ajax({ type: ...

Seeking a solution for resizing the Facebook plugin comments (fb-comments) using Angular when the window is resized

Is it possible to dynamically resize a Facebook plugin comment based on the window or browser size? I want the fb-comment div to automatically adjust its size to match the parent element when the browser window is resized. <div id="socialDiv" class="c ...

transferring data between react components

I am currently working on breaking down code into smaller components, starting with the snippet below from Rows.jsx. I am struggling to grasp how props are passed between parent and child components. Despite reading several guides and articles, I remain un ...

How can I integrate both the ui-bootstrap datepicker and timepicker in an AngularJS application?

I am currently developing a web application that utilizes UI-Bootstrap's datepicker and timepicker directives. The datepicker is set up as a simple popup dialog, while the timepicker appears on the page next to the datepicker. However, I am facing ch ...

Is it possible to scroll a div on mobile without the need for jQuery plugins?

Upon investigating the initial query, we managed to implement D3js for identifying a scroll event. This allowed us to scroll the div #scroll-content from any location on desktop devices. However, we encountered an issue where this method does not function ...

Tips for refreshing the <img> tag using a user image

I am currently designing a bootstrap webpage and trying to implement a feature where the user can input an image, which will then be displayed in a preview modal along with some text provided by the user. The modal is functioning correctly. Here is the co ...

Exploring the Vanilla JavaScript alternative to the jQuery.each() function

$.fn.slideUpTransition = function() { return this.each(function() { var $el = $(this); $el.css("max-height", "0"); $el.addClass("height-transition-hidden"); }); }; When utiliz ...

Error encountered during Atom execution - The command '/usr/bin/env: 'node' was not found in the directory

Just starting out with coding on Atom and I'm stuck dealing with the same error message every time I try to run my Javascript code. bash: line 1: node: command not found /usr/bin/env: ‘node’: No such file or directory I've searched for solu ...

Mastering the Art of Crafting an Effortless Slide Showcase

I have created a carousel that works fine except for one issue: when I reach the last image or go back from the first image, I want the image to be displayed. For example, when you click the right arrow after reaching the last image, it should show the fir ...

Tips for posting images upon clicking a div instead of a submit button

I previously had a code that allowed users to click on the submit button and have the text inside a contenteditable div passed to upload.php using JQuery, inserted into a database, and immediately displayed. Now, I want to modify this code to also handle i ...

Tips for retrieving the clicked word in JavaScript

Is it possible to retrieve the word that was right-clicked on along with its x, y coordinates? I attempted the following code:document.onclick=getTextOnClick; function getTextOnClick(e) { console.log(e); if (window.getSelection) { txt = wi ...

What is the trick to have a CSS element overflow the boundaries of its containing div entirely?

Currently, I have a JS Fiddle project where I am attempting to achieve a specific effect. In the project, there is a circle positioned at the center of a div. When the script runs, the circle expands evenly in all directions until it reaches the borders on ...

How can I incorporate the `name` parameter into a `redirect` URL using vue-router?

Below is the setup of my router in the Vue project import { createRouter, createWebHistory } from "vue-router"; const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: "/", ...

passing JSON data using JavaScript or jQuery

I have a JSON snippet that I need to parse using JavaScript or jQuery and convert into variables: name and meetup. Can you help me with this? Below is the JSON code: { "MYID": 1, "module": [ { "name": "Manchester", ...

Tired of the premium content on Medium.com. How can I conceal premium posts that are aimed at a specific class within a parent element?

I have noticed that all Premium posts contain an element with the class ="svgIcon-use" <svg class="svgIcon-use" width="15" height="15" viewBox="0 0 15 15" style=""><path d="M7.438 2.324c.034-.099.090 123 0l1.2 3.53a.29.29 0 0 0 .26.19h3.884c.11 0 ...

Invoke a function in a different component following the completion of an asynchronous task in a React.js application

I am working with 2 components in my project. The first component contains a function that needs to be called after an async function in the second component completes. I am looking for a way to achieve something similar to Vue's this.$emit() function ...

The compatibility issue between Vue 2.6.12 and Laravel is causing difficulties for FullCalendar to function properly

Recently, I attempted to integrate the fullcalendar library version 5.9.0 into my project following the instructions provided in the documentation. <script> import '@fullcalendar/core/vdom' // resolves Vite issue import FullCalendar from ...

Turn off email alerts for items and folders in ALFRESCO 5.2

Here's a snippet of JS code I created to toggle notifications with a button click: (Action.min.js): var me = this, jsNode = record.jsNode, content = jsNode.isContainer ? "folder" : "document"; if (jsNode.hasAspect("cm:emailed") ...

Why is it that when I refresh the page in Angular, my logged-in user is not being recognized? What could be causing this

I am developing a Single Page Application using the combination of Angular JS and Node JS. In my HTML file, I have defined two divs and based on certain conditions, I want to display one of them using ng-if. However, I noticed that the model value used in ...