Please note this not a duplicate Q.
I have a hard time figuring out the way to go from this JSON array, which is one level array and we can have the path of each obj or element in the "path" property
[
{
"name" : "a-1",
"path" : "a-1",
"parent": ""
},
{
"name" : "a-2",
"path" : "a-1>a-2",
"parent": "a-1"
},
{
"name" : "a-3",
"path" : "a-1>a-2>a-3",
"parent": "a-2"
},
{
"name" : "a-4",
"path" : "a-1>a-4",
"parent": "a-1"
},
{
"name" : "b-1",
"path" : "b-1",
"parent": ""
}
]
The final result should be as it follow,
[
{
"attr": {
"name": "a-1",
"path": "a-1",
"parent": ""
},
"children": [
{
"attr": {
"name": "a-2",
"path": "a-1>a-2",
"parent": "a-1"
},
"children": [
{
"attr": {
"name": "a-3",
"path": "a-1>a-2>a-3",
"parent": "a-2"
}
}
]
},
{
"attr": {
"name": "a-4",
"path": "a-1>a-4",
"parent": "a-1"
}
}
]
},
{
"attr": {
"name": "b-1",
"path": "b-1",
"parent": ""
}
}
]
I tried the to do so using the the parent with the Filter and find function
theOneLevelArray.filter((elt, idx, arr) => {
let parent = arr.find(e => e.componentItemNumber === elt.parentItemNumber);
if (!parent) return true;
(parent.children = parent.children || []).push(elt);
});
I tried also using a loop then applying a reduce function after 'split(">")' the path element (the code is really messy for this method this is why I didn't paste)