Combining elements from a string array to create a hierarchical object in JavaScript

I need assistance with merging values from an array into a predefined nested object. Here is an example of the array with values,

['name=ABC XYZ', 'hobbies=[M,N,O,P]', 'profession=S', 'age=27']

The object that needs to be updated with these values looks like this,

const person = {
    details_1: {
      name: null,
      hobbies: null,
      profession: null
    },
    details_2: {
      age: null
    }
  };

The desired output should resemble the following structure,

const updated_person = {
    details_1: {
      name: 'ABC XYZ',
      hobbies: [M,N,O,P],
      profession: 'S'
    },
    details_2: {
      age: 27
    }
  };

Your help on this matter is greatly appreciated!

Answer №1

This time, I approached the problem differently by creating a new solution. I decided to utilize an interface where I outlined the required data structure. In the following steps, I converted the string array into key and value pairs, filtering out the keys defined in the interface and storing them in an empty object literal.

const data = ["name=ABC XYZ", "hobbies=[M,N,O,P]", "profession=S", "age=27"];

const dataInterface = {
  details_1: { name: null, hobbies: null, profession: null },
  details_2: { age: null },
};

function orderData(arr) {
  const records = arr.map((item) => {
    let [key, value] = item.split("=");
    if (value[0] === "[" && value[value.length - 1] === "]") {
      value = value.slice(1, value.length - 1).split(",");
    }
    return { key, value };
  });

  const dataBlock = {};
  Object.keys(dataInterface).forEach((detail) => {
    dataBlock[detail] = {};
    Object.keys(dataInterface[detail]).forEach((dataKey) => {
      dataBlock[detail][dataKey] = records.filter((record) => {
        return record.key === dataKey;
      })[0].value;
    });
  });
  return dataBlock;
}

const orderedData = orderData(data);
console.log(orderedData);

Answer №2

One way to accomplish this task is by looping through the given array.

const data = ['name=John Doe', 'interests=[A,B,C]', 'occupation=X', 'age=30'];

const individual = {
  bio_1: {},
  bio_2: {}
};

data.forEach(element => {
  (element.split('=')[0] !== 'age') ? individual.bio_1[element.split('=')[0]] = element.split('=')[1] : individual.bio_2[element.split('=')[0]] = element.split('=')[1]
});

console.log(individual);

Answer №3

When trying to merge an unstructured array into a structured object in JavaScript, it can be challenging to ensure that the array values are correctly assigned to the corresponding properties in the object.

While JavaScript does offer the assign() function for merging objects, it is important that your source data matches the structure of the object and not just an array.

For example, transforming this array:

['name=ABC XYZ', 'hobbies=[M,N,O,P]', 'profession=S', 'age=27']

into an object like this:

const source = [{details_1: {"name":"ABC XYZ", "hobbies":"[M,N,O,P]", "profession":"S"}, details_2: {"age":"27"}}]

allows you to use Object.assign() to merge it with a structure like:

const person = {
  details_1: {
    name: null,
    hobbies: null,
    profession: null
  },
  details_2: {
    age: null
  }
};

You may need to create a new instance of person or clear it before using Object.assign(). Alternatively, if person is already an object, you could implement a fill() method to handle the array data accordingly.

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

Troubleshooting Angular JS Module Injection Issues

Lately, I've been exploring the wonders of angular JS and it has truly impressed me. However, one concept that still eludes my full understanding is injection. Despite this, I have successfully employed this technique across numerous pages in my proje ...

Use Ramda to convert an array of objects into nested objects

As a beginner, please forgive me for asking what may be considered a naive question. I currently have an array of objects const arr = [{id: 1, name: 'Pete'}, {id: 5, name: 'John'}, {id: 3, name: 'Peter'}] and I am looking to ...

Quickly view products in Opencart will automatically close after adding them to the cart and redirecting the

I've integrated the product quickview feature into my OpenCart theme, which opens a product in a popup. However, when I add a product to the cart from the popup, it doesn't update on the main page until I refresh. I'm looking for a way to re ...

Pagination with composite queries in Firestore allows for efficient retrieval of

Currently I am attempting to paginate a composite index query, let size = data.length let lastElement = data[size-1].commentCount db.collection('user-content').orderBy('commentCount','desc').orderBy('likes', 'd ...

Secure your data with public key encryption and decryption using the Crypto Module in NodeJS

I have a challenge with encrypting/decrypting data using a public key that is stored in a file. The code snippet below illustrates my approach: encryptWithKey (toEncrypt, publicKeyPath) { var publicKey = fs.readFileSync(publicKeyPath, "utf8"); ...

Guide to dynamically insert rows in HTML using Vue.js based on the selected option

This is the initial row. Depending on the selection made here, different rows will be displayed <div class="row"> <div class="col-md-4"> <div class="form-group label-floating"> <label class="control-label">Case Type< ...

Preventing default behavior in a JQuery post request

Encountering an issue with jQuery functionality on a mobile device. function send() { $.post("scripts/post.php", { username: $("input[name=username]").val(), password: $("input[name=password]").val() }, function(data) { if ($(".data div" ...

Extracting information from a designated website using Python, including pages with search functionality and javascript features

Visit the website where you will find a search input box in html. Input a company name into the search box, select the first suggestion from the drop-down menu (like "Anglo American plc"), navigate to the URL containing information about that specific com ...

Assign an event listener to a collection of elements

Suppose I have an Array containing elements and another Array consisting of objects in the exact same index order. My goal is to add a click event for each element that will display a specific property of each object. For instance: myDivArray = [ div0, d ...

A comprehensive guide on organizing JavaScript files within an Angular project

In the process of building my MEAN app, I have structured my folders in the following way: I have included a js file in /angular/src/assets/js for jQuery functionalities. To achieve this, I utilized npm to install jQuery. Now, I am faced with the task o ...

Learn how to dynamically modify the text and color of a column value within a <v-data-table> component in Vue.js 2.6.11 and Vuetify 2.2.11 based on a specific condition

In my current project where I am developing a web application using ASP.NET CORE for the backend and vue.js for the frontend, I encountered an issue with Vuetify's CRUD Datatable UI Component in a page named "Category". The problem arises when trying ...

how to ensure a consistent property value across all scopes in AngularJS

Here is my perspective <div ng-if="isMultiChoiceQuestion()"> <li class="displayAnswer" ng-repeat="choice in getMultiChoice() track by $index" ng-if="isNotEmpty(choice.text.length)"> <input type= ...

Tips for using parsley on a dynamically loaded webpage

I'm encountering an issue with applying validation for a datepicker in AJAX loaded content. The validation doesn't seem to work for the loaded content. Can someone please assist me with this? /Script/ function applyValidationForDatepicker(feest ...

Ways to alter the typography style if the text exceeds a certain length

I need some assistance with using Material UI in my ReactJs project with TypeScript. I am trying to decrease the font size of typography when the text exceeds 3 lines. Here is a snippet of my code: const checkFontSize =() => { if(text.leng ...

Code snippet in Java and JSON explaining the method to retrieve a specific element from a JSON object which includes an array of objects {[ {},{} ]}

Struggling with java+json and need some assistance. Greetings to everyone! My task is to sort data by song title and handle exceptional situations. I am required to write a method that can sort data from a json file based on specific fields. The parsing of ...

What is the purpose of requiring the explicit invocation of app.listen(port) to enable express-ws to function properly?

I've recently started exploring NodeJS Express and came across the official tutorial from express-ws for setting up websockets in a simple project generated using npx express-generator. While following the tutorial, I noticed that in the app.js file, ...

Tips for modifying and refreshing data in a live table with JQuery

One challenge I'm facing is figuring out how to transfer the data from a dynamic table back into input fields when clicking on the edit button of a specific row. Additionally, I need to update that particular row based on any changes made to the value ...

"Efficiently handle JSON and binary data passing with the enhanced functionality of Express Body Parser

Within my express app router, I have routes set up to handle both POST requests with JSON data and binary data. The issue arises when I use body parser to parse the JSON data, as it incorrectly interprets the binary data as JSON and causes errors during th ...

Discovering the Nearest Point to the Mouse Cursor using Three JS Ray Casting

Three.js version r85 While using raycasting in Three JS, a list of points is generated, and I am interested in identifying the point closest to the cursor. It appears that the first point returned is typically the one nearest to the camera. Is there a me ...

The collapsible section expands upon loading the page

Trying to implement Disqus as a plugin on my test webpage, I created a collapsible section with a "Show comments" button. The idea was to hide the plugin by default and reveal it only when users click on "Show comments". Despite using the w3schools example ...