Create nested array from flatten array which has corresponding flatten arrays using javascript
Without any external JS like underscore.js, lodash.js, If you want to create a nested array from flatten array which has corresponding flatten arrays, just do this simple method like below,
Original array,
[
{"Id":1,"title":"title","parent":null},
{"Id":2,"title":"title","parent":null},
{"Id":3,"title":"title","parent":2},
{"Id":4,"title":"title","parent":2},
{"Id":5,"title":"title","parent":3},
{"Id":7,"title":"title","parent":4},
{"Id":8,"title":"title","parent":4}
]
expected,
[
{"Id": 1, "title": "title", "parent": 0, "children": [
{"Id": 3, "title": "title", "parent": 1, "children": [
{"Id": 4, "title": "title", "parent": 3, "children": [
{"Id": 5, "title": "title", "parent": 4},
{"Id": 6, "title": "title", "parent": 4}
]},
{"Id": 7, "title": "title", "parent": 3}
]}
]},
{"Id": 2, "title": "title", "parent": 0, "children": [
{"Id": 8, "title": "title", "parent": 2}
]}
]
method,
let data = [
{ "Id": 1, "title": "title", "parent": null },
{ "Id": 2, "title": "title", "parent": null },
{ "Id": 3, "title": "title", "parent": 2 },
{ "Id": 4, "title": "title", "parent": 2 },
{ "Id": 5, "title": "title", "parent": 3 },
{ "Id": 7, "title": "title", "parent": 4 },
{ "Id": 8, "title": "title", "parent": 4 }
]
function arrayNesting() {
return data.reduce((acc, obj) => {
if (obj.parent) {
data.map((o) => {
if (o.Id === obj.parent) {
if (!o.children) o.children = [];
o.children.push(obj);
}
return o;
});
} else {
acc.push(obj);
}
return acc
}, []);
}
console.log(arrayNesting());
Hope this is helpful, Thanks for reading.