I have an array of objects that can have other arrays of object as children (it can have a complex hierarchy): if an object has a children prop — it's a group, if it doesn't — it's an item:
var myData = [
{
"name": "item 1"
},
{
"name": "group 1",
"children": [
{
"name": "item in a group 1"
}]
},
{
"name": "group 2",
"children": [
{
"name": "group 1 in a group 2",
"children": [
{
"name": "item in a nested group 1"
},
{
"name": "deeply nested group",
"children": [
{
"name": "deep item"
}]
},]
},
{
"name": "group 2 in a group 2",
"children": [
{
"name": "item in a nested group 2"
}]
}]
}]
and I want to parse it to have a flat object that would have all groups as props and items as arrays, each prop would also include items from grandchildren groups.
Currently with the code below I'm able to flatten the array and have groups as props and items as arrays for each object:
{
"root": [
"item 1"
],
"group 1": [
"item in a group 1"
],
"group 2": [],
"group 1 in a group 2": [
"item in a nested group 1"
],
"deeply nested group": [
"deep item"
],
"group 2 in a group 2": [
"item in a nested group 2"
]
}
However I 'm struggling with adding grandchildren. Here's the desired output:
{
"root": [
"item 1"
],
"group 1": [
"item in a group 1"
],
"group 2": [
"item in a nested group 1", // includes items of child groups
"item in a nested group 2",
"deep item"
],
"group 1 in a group 2": [
"item in a nested group 1",
"deep item" // includes item of a child group
],
"deeply nested group": [
"deep item"
],
"group 2 in a group 2": [
"item in a nested group 2"
]
}
here's my code I'm using (I can only use older version of pure JS so no ES6, NPM; can use polyfill though)
var myItems = {
'root': []
}
var i;
for (i = 0; i < myData.length; i++)
{
parseItems(myData[i], 'root')
}
function parseItems(data, groupName)
{
var key, i;
for (key in data)
{
if (!data.hasOwnProperty(key))
continue;
else if (data.hasOwnProperty('children'))
{
groupName = data['name']
if (myItems[groupName] == undefined) myItems[groupName] = []
for (i = 0; i < data[key].length; i++)
{
parseItems(data[key][i], groupName);
}
}
else
{
myItems[groupName].push(data['name']);
}
}
}
And I don't understand how can I make a version of this code (or something better probably?) that'd fill parent groups with grandchildren items.
"group 1"in"root"?rootfor items that are on top level of the array but aren't groups (likeitem 1)