Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

344
Views
How to create nested JSON using first entry from from flat JSON as parent in javascript

I've tried various answers to this (same/similar) question here, and none have given the desired result. I have a flat Json file that I need to convert to nested. The first item in each chunk is the item that the data needs grouping on when converted to nested data. The example data just shows two "types" but there are several more in the data, and a few more other elements along with colour and size as well - I kept it short for posting here.

Example data input:

[
  {
    "type": "Background",
    "colour": "Blue",
    "size": "5"
  },
  {
    "type": "Background",
    "colour": "Grey",
    "size": "3"
  },
  {
    "type": "Foreground",
    "colour": "Red",
    "size": "5"
  },
  {
    "type": "Foreground",
    "colour": "White",
    "size": "10"
  }
]

Desired Output:

[
  {
    "type": "Background",
    "elements": [
      {
        "colour": "Blue",
        "size": "5"
      },
      {
        "colour": "Grey",
        "size": "3"
      }
    ]
  }
  {
    "type": "Foreground",
    "elements": [
      {
        "colour": "Red",
        "size": "5"
      },
      {
        "colour": "White",
        "size": "10"
      }
    ]
  }
]

The closest I came to an answer for this was here: Create nested json from flattened JSON in javascript

But the output I received from that (in VSCode) was this:

{
  type: { elements: [ [Object], [Object] ] }
}

While I am trying to follow the code, it is beyond my javascript knowledge currently, so I don't know what's going wrong, or why I get [object] and not the actual elements?

Can anyone help me get this sorted out so my output looks like my above "Desired output"?

Cheers!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use the forEach() method to loop over the array, in this case, result. If the type wasn't set in the result, then add the new type. But, if the item already has its type in the result, then just push the item's elements.

const items = [
  {
    type: 'Background',
    colour: 'Blue',
    size: '5',
  },
  {
    type: 'Background',
    colour: 'Grey',
    size: '3',
  },
  {
    type: 'Foreground',
    colour: 'Red',
    size: '5',
  },
  {
    type: 'Foreground',
    colour: 'White',
    size: '10',
  },
];

let result = [];

items.forEach((item) => {
  if (!result.find((x) => x.type === item.type)) {
    result.push({ type: item.type, elements: [] });
  }

  result
    .find((x) => x.type === item.type)
    .elements.push({
      color: item.colour,
      size: item.size,
    });
});

console.log(result);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

about 4 years ago · Juan Pablo Isaza Report

0

try this

var output = [];

var newObj = { type: input[0].type, elements: [] };
var prevType = input[0].type;

input.forEach((element) => {
  if (element.type != prevType) {
    output.push(newObj);
    newObj = { type: element.type, elements: [] };
    prevType = element.type;
  }
  newObj.elements.push({ colour: element.colour, size: element.size });
});
output.push(newObj);
about 4 years ago · Juan Pablo Isaza Report

0

It seems that there are two steps here. First group all entries with the same type (which would be easier under the type name as a property, then build the nesting.

const input = 
    [
      {
        "type": "Background",
        "colour": "Blue",
        "size": "5"
      },
      {
        "type": "Background",
        "colour": "Grey",
        "size": "3"
      },
      {
        "type": "Foreground",
        "colour": "Red",
        "size": "5"
      },
      {
        "type": "Foreground",
        "colour": "White",
        "size": "10"
      }
    ];

var assist = {},
    output = [];

// Group original objects based on type
// The type is used as a property value
for (let i = 0; i < input.length; i++) {
  let type = input[i].type;
  
  if (assist.hasOwnProperty(type)) {
    assist[type].push(input[i]);
  } else {
    assist[type] = [input[i]];
  }
  delete input[i].type;
}


// Turn the grouped entries into new array entries
let keys = Object.keys(assist);
for (let i = 0; i < keys.length; i++) {
  output.push({
    type: keys[i],
    elements: assist[keys[i]]
  });
};

// Show results
console.log(output);

Note that while the above code does not modify the original array, it does modify it's members (deleting their type property) and using them in the output array. You will have to clone it if you need the original too.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!