I would like to get the hierarchy of every single element of the array
I have this object array
[
{
"id": "1",
"name": "Car",
"parentId": "0",
"parents": []
},
{
"id": "2",
"name": "Car > Steering wheel",
"parentId": "1",
"parents": []
},
{
"id": "3",
"name": "Car > Wheel",
"parentId": "1",
"parents": []
},
{
"id": "4",
"name": "Car > Wheel > Wheel rim",
"parentId": "3",
"parents": []
},
{
"id": "5",
"name": "Bus",
"parentId": "0",
"parents": []
},
{
"id": "6",
"name": "Bus > Wheel",
"parentId": "5",
"parents": []
}
]
The result I need to get is the following array with the ‘parents’ key set
[
{
"id": "1",
"name": "Car",
"parentId": "0",
"parents": ["1"]
},
{
"id": "2",
"name": "Car > Steering wheel",
"parentId": "1",
"parents": ["1","2"]
},
{
"id": "3",
"name": "Car > Wheel",
"parentId": "1",
"parents": ["1","3"]
},
{
"id": "4",
"name": "Car > Wheel > Wheel rim",
"parentId": "3",
"parents": ["1","3","4"]
},
{
"id": "5",
"name": "Bus",
"parentId": "0",
"parents": ["5"]
},
{
"id": "6",
"name": "Bus > Wheel",
"parentId": "5",
"parents": ["5","6"]
}
]
As you can see, ‘parents’ contains its ID and its parents IDs.
I tried with map but failed. What do you suggest I do?
I tried this but I know it’s not good
let arr = [];
for (let i = 0; i < flattenArray.length; i++) {
let node = flattenArray[i];
let id = node.id;
let parentId = node.parentId;
if (parentId != "0") {
node.parents = [id, parentId];
arr.push(node);
} else {
node.parents = [id];
arr.push(node);
}
}
2
Answers
There are a couple things that need to be done.