Generate a nested object by combining multiple objects within an array using JavaScript

I am working with a nested array of objects, shown below:

[       
          {
            "i18n Key": "messages.titles.info",
            English: "Info",
            Spanish: "Info",
          },
          {
            "i18n Key": "messages.titles.export",
            English: "Export",
            Spanish: "Exportar",
          },
          {
            "i18n Key": "messages.common.pleaseWait",
            English: "Please Wait…",
            Spanish: "Por favor esperar…",
          },
          {
            "i18n Key": "messages.common.errors.couldNotAccessADGroup",
            English: "Could not access AD to get user groups. Please try again.",
            Spanish: "No se puede acceder a AD para buscar grupos de usuarios. Por favor inténtelo nuevamente.",
          },
          {
            "i18n Key": "labels.country.regulatorList.regulatorForm.regulatorName",
            English: "Regulator Name",
            Spanish: "Nombre del regulador",
          },
          {
            "i18n Key": "labels.country.regulatorList.regulatorForm.country",
            English: "Country",
            Spanish: "País",
          },
]  

How can I transform this into a nested object structure like the one below?

{
    "messages": {
      "titles": {
        "info": "Info",
        "export": "Exportar",
      },
      "common":{
        "pleaseWait":  "Por favor esperar…",
        "errors": {
            "couldNotAccessADGroup": "No se puede acceder a AD para buscar grupos de usuarios. Por favor inténtelo nuevamente.",
        }    
      },
    }  
    "labels":{
        "country":{
            "regulatorList":{
                "regulatorForm":{
                    "regulatorName":  "Nombre del regulador",
                    "country": "País",
                }
            }
        }
    }
}

The length of the "i18n Key" varies and it is based on the last word. The corresponding Spanish value should be retained.

Any assistance on achieving this would be highly appreciated.

Answer №1

Considering that the i18n Key value plays a crucial role in determining the output structure and may vary in length, my recommendation is to implement recursion as a solution for this issue.

Solution

// Input data
const descriptors = [
  {
    "i18n Key": "messages.titles.info",
    English: "Info",
    Spanish: "Info",
  },
  {
    "i18n Key": "messages.titles.export",
    English: "Export",
    Spanish: "Exportar",
  },
  {
    "i18n Key": "messages.common.pleaseWait",
    English: "Please Wait…",
    Spanish: "Por favor esperar…",
  },
  {
    "i18n Key": "messages.common.errors.couldNotAccessADGroup",
    English: "Could not access AD to get user groups. Please try again.",
    Spanish: "No se puede acceder a AD para buscar grupos de usuarios. Por favor inténtelo nuevamente.",
  },
  {
    "i18n Key": "labels.country.regulatorList.regulatorForm.regulatorName",
    English: "Regulator Name",
    Spanish: "Nombre del regulador",
  },
  {
    "i18n Key": "labels.country.regulatorList.regulatorForm.country",
    English: "Country",
    Spanish: "País",
  },
];

const sourceValue = 'Spanish';

const output = {};

const parseValue = (obj, value = undefined, keyMap = []) => {
  if (keyMap.length) {
    const propertie = keyMap.splice(0, 1);

    if (!Object.prototype.hasOwnProperty.call(obj, propertie)) {
      obj[propertie] = {};
    }

    if (!keyMap.length) {
      obj[propertie] = value;
    } else {
      obj[propertie] = parseValue(obj[propertie], value, keyMap);
    }
  }
  return obj;
};

for (let i = 0; i < descriptors.length; i++) {
  const descriptor = descriptors[i];
  const keyMap = descriptor['i18n Key'].split('.');
  
  parseValue(output, descriptor[sourceValue], keyMap);
}

console.log(JSON.stringify(output, null, 2));

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

Removing an item from an array while also updating one of its attributes in JavaScript

I am facing a challenge with this list of objects: const flights = [ { id: 00, to: "New York", from: "Barcelona", cost: 700, scale: false }, { id: 01, to: "Los Angeles", from: "Madrid", cost: 1100, scale: tru ...

Python code that converts a NumPy array into a string representation

Is there a way to obtain the complete string representation of a 2D float32 array with dimensions 512x512? Currently, when using either numpy's string2array(array) or repr(array), I only get a truncated output like this: '...[2.0886018e-04 1.702 ...

Unable to transmit a collection of JavaScript objects in a node.js environment

Below is the code snippet I am currently working with: app.get('/posts',function(req,res){ console.log(posts); res.send(posts); res.send(200); }); I am using the following approach to retrieve and display an array of JavaScript objects (posts ...

What is the best way to send data from a child functional component to a parent class component?

I am facing a situation where I have a parent class component and a child functional component. While there are examples available on passing values from a child class component to a parent class component, I am wondering how to pass a value from this type ...

Rendering with node.js express inside nested JS files

Imagine I have a basic view <html> <head> <title>something</title> </head> <body> <%= param %> </body> <script type="text/javascript" src="myscript.js"></script> </html> Be ...

Angularjs $state.go is a powerful tool for navigating through different states

I've been working on setting up a basic navigation system for my single-page application. It consists of a series of links in a list, each linked to a method in a NavigationController. The method then triggers $state.go by passing it a state string. I ...

Having trouble with loading the contents of an iframe in JavaScript?

Within my website, there is a single Iframe that I set the src attribute for during the document.ready event. I have placed this iframe inside a jquery UI dialog, but now every time the dialog is opened, the Iframe reloads its contents. I would like this ...

JavaScript Code - Modify text color

I am working on a task to create a function called "tousVerts" which translates to "everythingGreen" in French. The goal of this function is to change the color of specific text on the page to green. This text is enclosed within either EM or A html tags. I ...

Array logging mistakenly outputs a number

I needed to access the data from JSON outside of the xml function so that I could use it in multiple functions. When I initially logged the data, it displayed arrays with objects in it. However, when I checked the length instead, it returned zero. After re ...

The combination of Spring Boot and Angular's routeProvider is a powerful

I have been working on a project using Spring Boot, REST, and AngularJS. While I successfully implemented the back end with REST, this is my first time using AngularJS. Despite watching numerous tutorials and following them step by step, I am still facing ...

What is the process for obtaining a JSON result after completing an upload?

I recently started working with the razor view engine and I have encountered a situation where I need to upload an image using the Change event of an image browser. The jQuery function for this task is as follows: $("#billUpload").change(function (){ ...

Troubleshooting a jQuery issue involving socket.io

I recently created a chat room using socket.io and jQuery. Inexperienced with node.js, I uploaded the files to an old FTP to get it online. Upon loading the website, I encountered an error in the console: Uncaught ReferenceError: io is not defined at ...

Generate a customizable form by utilizing a JSON file as a template. The JSON file can be easily modified by clicking a button, allowing for real-time

My goal is to develop a dynamic form using the guide provided at https://angular.io/guide/dynamic-form. I am utilizing two JSON files, namely sbb.json and gx.json. The initial creation of the form from the JSON file works flawlessly. However, I encountered ...

Typescript Array does not adhere to correct data type

Why does the code below fail to transpile when pushing a new instance of class B into an array that is typed as only accepting instances of class A? class A {}; class B {}; const arr: A[] = []; arr.push(new B()); ...

Maintain text area spacing using JavaScript

Could anyone assist me in finding a script that can change line breaks from a user's textarea input into HTML upon form submission to ensure that the formatting is maintained in our notification emails? Currently, I am encountering an issue where fie ...

What is the best way to set the theme for Material-UI in a React application?

I find myself puzzled when it comes to styling a front-end based on Material-UI. Can someone clarify where the theme originates from in the following example code and what impact the theme has? import React from "react"; import Container from "@material- ...

The omission of form field values is causing the Auto POST Form on Interval to be incomplete

There is a script that functions correctly when a button is clicked to submit the form. However, when I change the form to automatically post on an interval, the values in the form fields are not included in the submission. I believe this issue is relate ...

How can I update the Page Controller index in Swift 3 when scrolling through a UICollectionView?

After searching for quite some time, I still can't seem to find the answer to my question. The issue at hand is with a UICollectionView set up in Horizontal Scroll Direction with Paging Controller. Click here to view the image path. I'm loading ...

Delete progeny from Object3D

If I were to instantiate objects using the code below: const group = new THREE.Object3D(); for (let i = 0; i < 10; i++) { const geometry = new THREE.BoxGeometry(1, 1, 1); const material = new THREE.MeshNormalMaterial(); const mesh = new T ...

Leveraging the back button in an AngularJS Mobile SPA

Utilizing AngularJS for my Single Page App (SPA), I am currently exploring the most effective way to handle the back button functionality on mobile devices. My setup involves a single JavaScript file, one HTML page, and no partials. The content is reveale ...