Transforming an array in JavaScript into a JSON object

I'm currently working on creating a loop in JavaScript or jQuery to generate a new JSON object from an array. The goal is to convert an input JavaScript array into a desired format for the output. Here's the input array:

INPUT:

    [
      {
        "parent": "parent_1",
        "child": "abc",
        "data": "data1"
      },
      ...

From the above array, I need a loop that will produce the following JSON object structure:

OUTPUT:

[
  {
    "parent_1": {
      "child": [
        {
          "name": "abc",
          "data": "data1"
        },
        ...
      ]
    }
  },
    ...
]

Answer №1

To organize the information, you can group the data by using the parent key as a reference for an object and then include the remaining object properties in the children array of that specific group.

This method ensures that the original data remains unchanged.

const
    data = [{ parent: "parent_1", child: "abc", data: "data1" }, { parent: "parent_1", child: "def", data: "data2" }, { parent: "parent_1", child: "ghi", data: "data3" }, { parent: "parent_2", child: "jkl", data: "data4" }, { parent: "parent_2", child: "acc", data: "data5" }, { parent: "parent_3", child: "mjh", data: "data6" }, { parent: "parent_3", child: "fg1", data: "data7" }, { parent: "parent_2", child: "dfg", data: "data8" }, { parent: "parent_3", child: "jkk", data: "data9" }, { parent: "parent_4", child: "3ff", data: "data10" }, { parent: "parent_3", child: "mhg", data: "data11" }, { parent: "parent_1", child: "gnh", data: "data12" }],
    result = Object.values(data.reduce((r, { parent, ...o }) => {
        r[parent] ??= { [parent]: { children: [] } };
        r[parent][parent].children.push(o);
        return r;
    }, []));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Here is a solution that might work for you:

function restructureArray(arr, key) {
  const obj = {};
  arr.forEach(item => {
    const value = item[key];
    if (!Array.isArray(obj[value])) obj[value] = [];
    delete item[key];
    obj[value].push(item);
  });

  return Object.keys(obj).map(value => {
    return { [value]: { items: obj[value] } };
  });
}

To use this function, simply call it like this:

restructureArray(*yourArray*, "category")

Answer №3

One way to achieve this is by using the .reduce method in JavaScript:

let items = [ {name: 'item 1', category: 'category-1'}, {name: 'item 2', category: 'category-2'} ]

let resultObject = items.reduce(function(obj, item) {
      if (!obj[item.category]) obj[item.category] = {children: []};
      obj[item.category].children.push(item);
      return obj;
}, {})
console.log(resultObject);

Answer №4

If you're looking to achieve this particular task, the code snippet below will help you get there.

var sampleArray = [{"parent":"parent_1","child":"abc","data":"data1"},{"parent":"parent_1","child":"def","data":"data2"},{"parent":"parent_1","child":"ghi","data":"data3"},{"parent":"parent_2","child":"jkl","data":"data4"},{"parent":"parent_2","child":"acc","data":"data5"},{"parent":"parent_3","child":"mjh","data":"data6"},{"parent":"parent_3","child":"fg1","data":"data7"},{"parent":"parent_2","child":"dfg","data":"data8"},{"parent":"parent_3","child":"jkk","data":"data9"},{"parent":"parent_4","child":"3ff","data":"data10"},{"parent":"parent_3","child":"mhg","data":"data11"},{"parent":"parent_1","child":"gnh","data":"data12"}];

var finalResult = {};

$.each(sampleArray, function (index, item) {
    if(!finalResult[item.parent]) {
        finalResult[item.parent] = [];
    }
    var childData = {'child': {'name': item.child, 'data': item.data}};
    (finalResult[item.parent]).push(childData);
});

console.log(finalResult)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

The headers are correct, however Chrome is displaying the message "Resource interpreted as Document."

After reading numerous queries like this, I'm still struggling to find a solution... I utilize the archiver and express Node.js modules. My goal is to effortlessly send a zip file to the client. Here's a snippet of my code: res.set("Content-Typ ...

Issues with jQuery .on() hover functionality in HTML5 select element not being resolved

I'm currently working on capturing the event triggered when the mouse hovers over a select box, regardless of whether it's collapsed or expanded. My approach involves using .on() in the following manner: $(document).on('hover', "select ...

Exploring the versatility of Grails 3 profiles through JSON rendering and implementing a One to Many relationship with

I am currently utilizing gson and web profile in my project. The domain I am working with is: package json import grails.rest.* @Resource(readOnly = false, formats = ['json', 'xml']) class Hero { String name String data S ...

Is it feasible to develop an asynchronous function in Node.js that executes concurrently?

My objective is to simultaneously execute the longRunnigTask and quickTask functions: function longRunnigTask() { return new Promise((resolve) => { console.log('longRunnigTask started'); for (let i = 0; i < 999999999; i+ ...

What is the best way to save request URLs in JavaScript while following the DRY principle?

Is there a standard practice in JavaScript for storing the URLs of endpoints used in AJAX applications? Would you, for instance, consider creating a "Service" class to encapsulate the URLs? ...

Optimizing Backend Access with Laravel and Vue JS: How to Choose the Most Effective Approach

Currently, I am utilizing Laravel API passport to handle authentication in my Single Page Application (SPA) built with Vue. At the moment, whenever I need to access the backend server, I have to include a header in order to be allowed through the protected ...

Looking to modify the contents of a shopping cart by utilizing javascript/jQuery to add or remove items?

I'm dealing with a challenge on my assignment. I've been tasked with creating a Shopping Cart using Javascript, HTML5, and JQuery. It needs to collect all the items from the shop inside an Array. While I believe I have most of it figured out, I a ...

Display or conceal certain HTML form elements based on the selection made in the previous form element

I need assistance with a function that can dynamically show or hide certain HTML form elements based on the user's previous selection using JavaScript. For example, if a user selects "Bleached" from the Dyingtype drop-down menu, there is no need to di ...

The href attribute is not functioning correctly on Internet Explorer version 8

When dynamically generating HTML and appending the response to a DIV, here is the jQuery code: {% elif topic|length < 1 or topic.user_exhausted_attempts %} $('.questionHolder').hide(); var html = '<section class="span9">&a ...

React.js - "Encountered error: Unable to access 'map' property of undefined variable"

I've tried various methods I found through searching, but none of them seem to be working. Why is it still showing that map is undefined? import TextField from '@material-ui/core/TextField'; import Autocomplete from '@material-ui/lab/A ...

What is the best method for breaking down this JSON data into distinct 'objects'?

I am struggling with deserializing JSON data into multiple instances of an object I have defined. Here is how the object is structured: function Question_Value__c () { this.Id=null; this.Name=null; this.Question__c=null; this.Order__c=null ...

Is there a way to retrieve consecutive rows from mysql_fetch_assoc() in a separate file and store them in an array variable?

I am currently working on creating a simple "list-out" feature for displaying places/spots within a city from a table. To achieve this, I have set up a Place class and implemented a "get" function that returns an array using mysql_fetch_assoc(). This setup ...

How can I break down an object with hyphenated key names?

Attempting to perform object destructuring on the following: { name: "Bryan", last-name: "Enid" } However, trying to destructure it like this is not successful: const {name, last-name} = req.body Is there an alternative method to destructure this ...

transmit information to a FLUTTER server

I attempted to follow the instructions provided at in order to send data, but unfortunately, my code is not functioning as expected. I am unsure of what the issue may be. Could someone please assist me by pointing out any errors or recommending a helpful ...

Stop submission of form using react by implementing e.preventDefault();

Having trouble figuring this out.... Which event should I use to bind a function call for e.preventDefault(); when someone clicks enter in the input tag? Currently experiencing an unwanted refresh. I just want to trigger another function when the enter k ...

Issue with MongoDB find() function not retrieving any results (Assignment)

I am currently working on an assignment that requires the use of noSQL databases. Although I understand most of the queries we have to perform in mongoDb, every query I execute seems to return a blank result. Initially, we are required to create a collect ...

Having trouble retrieving JSON data from the server in an Android application

I have been working on an Android project where I need to fetch a JSON file from a specified URL. This JSON file contains the URLs for both the video and the image thumbnail that are supposed to be displayed in the app. However, I'm encountering an i ...

Error: protractor encountered an unexpected issue

Currently, I am following this tutorial I went through all the steps mentioned in the tutorial except for what was suggested in this post instead of npm install -g protractor I opted for npm install -g protractor --no-optional So far, I have succe ...

dynamic text overlay on a bootstrap carousel

Having limited knowledge in html and css, I am using a bootstrap carousel slider with text. I am trying to change the color of the box randomly. https://i.sstatic.net/TozUP.jpg Here is the code that I am currently using: <ol class="carousel-indicato ...

How come an <a> tag is nabbing mouse clicks from a <canvas> element?

I have been experimenting with creating a 3D piano using three.js. Here is a snippet of the code I am currently working on: let renderer, camera, scene, light, keys, selectedKey; init(); render(); function init() { // Code for initializing renderer, ...