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!