Transforming arrays into nested objects using JavaScript

My array consists of objects structured like this:

var exampleArray = [{
  name: 'name1',
  subname: 'subname1',
  symbolname: 'symbol1'
},
{
  name: 'name1',
  subname: 'subname11',
  symbolname: 'symbol11'
},
{
  name: 'name2',
  subname: 'subname2',
  symbolname: 'symbol2'
},
{
  name: 'name2',
  subname: 'subname22',
  symbolname: 'symbol22'
},
{
  name: 'name3',
  subname: 'subname3',
  symbolname: 'symbol3'
},
{
  name: 'name3',
  subname: 'subname33',
  symbolname: 'symbol33'
}];

I aim to transform this array into a hierarchical object, where the 'name' property will be the parent of 'subname', and 'subname' will be the parent of 'symbolname'. Here is an example of the desired structure:

result = {
  name1: {
    subname1: [symbolname1],
    subname11: [symbolname11] 
  },
  name2: {
    subname2: [symbolname2],
    subname22: [symbolname22] 
  },
  name3: {
    subname3: [symbolname3],
    subname33: [symbolname33] 
  }
}

I attempted to use the reduce method in my code as shown below:

exampleArray.reduce((object, item) => {
   object[item.name] = {[item.subname]: [item.symbolname]}
},{})

However, I encountered an issue where it only returned one subname. Any suggestions on how to resolve this? Thank you for your help.

Answer №1

reduce function requires a specific return value format:

var testArray = [{"name":"name1","subname":"subname1","symbolname":"symbol1"},{"name":"name1","subname":"subname11","symbolname":"symbol11"},{"name":"name2","subname":"subname2","symbolname":"symbol2"},{"name":"name2","subname":"subname22","symbolname":"symbol22"},{"name":"name3","subname":"subname3","symbolname":"symbol3"},{"name":"name3","subname":"subname33","symbolname":"symbol33"}]

var output = testArray.reduce((obj, item) => {
  obj[item.name] = obj[item.name] || {}; //Initialize 'name' if it doesn't exist
  obj[item.name][item.subname] = [item.symbolname];
  return obj;
}, {})

console.log(output);


If there are multiple symbolnames for a given subname, you can do the following:

var testArray = [{"name":"name1","subname":"subname1","symbolname":"symbol1"},{"name":"name1","subname":"subname11","symbolname":"symbol11"},{"name":"name2","subname":"subname2","symbolname":"symbol2"},{"name":"name2","subname":"subname22","symbolname":"symbol22"},{"name":"name3","subname":"subname3","symbolname":"symbol3"},{"name":"name3","subname":"subname33","symbolname":"symbol33"}];

var output = testArray.reduce((obj, item) => {
  obj[item.name] = obj[item.name] || {}; //Initialize 'name' if it doesn't exist
  obj[item.name][item.subname] = obj[item.name][item.subname] || []; //Initialize 'subname' if it doesn't exist
  obj[item.name][item.subname].push(item.symbolname); //Push the symbolname
  return obj;
}, {});

console.log(output);

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

Angularjs - Navigating the Depths of OrderBy: Effective Strategies for Handling Complex Sorting Structures

I have a collection of Incidents (displayed as an array below) that I need to sort meticulously by State, Priority, and Start_date. Specifically, I want them ordered in the sequence of Initial > Ongoing > InReview > Resolved for State, then Priori ...

Tips on accessing the v-model value with a parameter in VUE

Looking to access the v-model value using a parameter, I attempted the following code: <template> <div v-for="(item, idx) in data"> <input :id="item" :v-model="item"></input> <button @click=&q ...

Continuously looping in Firefox on Android is the setInterval function

I have a brief section of JavaScript that I would like to use to check a server every few seconds and update the DOM. function updateCard() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState ...

Trouble with an external .js script

function displayMessage() { var isConfirmed = confirm("Do you want to proceed?"); if (isConfirmed) { window.location = "./proceed"; } }; function checkIfEmpty(){ console.log("checkIfEmpty"); }; @CHARSET "ISO-8859-1"; form { margin:0 auto; width:300px ...

Using JQuery, a button is programmed to take a URL and then proceed to submit

My application is designed to shorten URLs for users who are authenticated. The form only requires the full URL input, and it will then generate a shortened version of the link. I am interested in creating a button that can be embedded on pages with long, ...

I'm curious if someone can provide an explanation for `<->` in TypeScript

Just getting started with TypeScript. Can someone explain the meaning of this symbol <->? And, is ProductList actually a function in the code below? export const ProductList: React.FC<-> = ({ displayLoader, hasNextPage, notFound, on ...

Ensuring the authenticity of dynamic forms

jQuery(document).ready(function(){ $("#submitButton").click(function () { if ( $("#formToSubmit").validationEngine('validate') == true) { $("#formToSubmit").submit(); } }); Utilizing the Validation Engine plugin for jQuery to valida ...

Eclipse - enhancing outline view by utilizing require.js define(...)

My code is structured within the define(...) function in the following format: define(['angular'], function(angular) { function foo () { console.log("Hi") ; } function foo2 () { console.log("Hi") ...

The initialization of the Angular service is experiencing issues

I have a service in place that checks user authentication to determine whether to redirect them to the login page or the logged-in area. services.js: var servicesModule = angular.module('servicesModule', []); servicesModule.service('login ...

What are the steps to ensure that this iframe adjusts perfectly to the page in terms of both vertical and horizontal dimensions

I have a sandbox from Material UI that you can view at this link: https://codesandbox.io/s/material-demo-forked-c8e39?file=/demo.js Upon loading the page, an iframe displays some HTML content. Although the width fits perfectly, there are two vertical scro ...

Is it possible for jQuery to analyze HTML contained within a variable?

Currently, I am utilizing PHP along with an ajax command to retrieve the complete HTML content from an external webpage using the file_get_contents() function in PHP. After storing this HTML in a JavaScript variable, I am curious if it is possible to uti ...

Pressing the cancel button triggers a refresh of the page within the iframe

I currently have an iframe embedded in my website, and within it is the following jQuery code: $(document).ready(function() { $('#print_button').click(function() { window.print(); }); }); The issue at hand is that when I click ...

It seems that JavaScript is unable to detect newly added elements following an AJAX request

One issue I'm facing is that when an element loads data based on a clicked block, all javascript functionalities break. Currently, using Ajax, I load an entire PHP file into my index after sending a variable to it. For example: If Block 1 is clicked ...

Implementing global parameters in ui-router

Currently, I am utilizing ui-router in AngularJS as shown below: .state ('browse.category', { url: "/:category", templateUrl: "views/browseCategory.html", controller: function($stateParams, $scope) { $scope.params = $st ...

Is it possible to define a data type from an external package using TypeScript and Node.js?

I'm currently in the process of reorganizing some code to utilize a list of signals and connect `.once` handlers to each one individually. const terminationSignals = ["SIGINT", "SIGUSR2", "SIGTERM"]; terminationSignals.f ...

Angular: promptly exit out of ngClick event handler

I have a selection menu on my webpage that is essentially an unordered list, with each item in the menu formatted like this: <li ng-click='doCalc(5)'>Five</li> The doCalc function that is triggered by clicking on these items may tak ...

Using jQuery code within PHP pages is a convenient and powerful way to

I am currently facing an issue with PHP and jQuery. Here is the structure of my website: header.php - contains all css and js files. index.php - main page. sidemenu.php - includes the side menu in index.php Within sidemenu.php, I have the following JS ...

Dynamic Data Causes Highcharts Date Formatting to Adapt

I wanted to create a line graph using Highcharts with the Date Format on x-axis set to "%b %e". For example, I expected 06/27/2014 to be displayed as Jun 17. Despite setting the date-format correctly, Highcharts seems to automatically change it when rende ...

Determine the number of network requests being made on a webpage

In my quest to develop a universal method using selenium, I am seeking a way to ensure that all background network activities, including Ajax, Angular, and API calls, have completed. While I am aware of the option to determine the number of active Ajax cal ...

Transferring a JavaScript variable to PHP using Ajax within the same webpage

Check out my HTML and JavaScript code: <form id="form" action="javascript:void(0)"> <input type="submit" id="submit-reg" value="Register" class="submit button" onclick="showtemplate('anniversary')" style='font-family: georgia;font- ...