I've an array of objects like this
[
{id :1, parent : null, title:test},
{id :2, parent : 1, title:test2},
{id :3, parent : 2, title:test3},
.
.
.
]
and need function to arrange like this Output :
[
{id :1, parent : null, title:test,
sub:[
{id :2, parent : 1, title:test2,
sub :[
{id :3, parent : 2, title:test3},
]
},
]},
.
.
.
]
And so handle deep nested
CodePudding user response:
something like this should do what you requested:
function nestArrays(arr) {
let retval = [];
for (let i = data.length - 1; i >= 0; i--) {
const isLastElement = i < data.length - 1;
retval.push(
isLastElement
? {
...data[i],
sub: [retval[retval.length - 1]],
}
: data[i]
);
}
return retval;
}
CodePudding user response:
You could iterate over your objects, try to find its the parent by ID, create a sub
property on the parent if it does not exist, and finally push the current object to the sub
array:
const objects = [
{ id: 1, parent: null, title: "test" },
{ id: 2, parent: 1, title: "test2" },
{ id: 3, parent: 2, title: "test3" },
{ id: 4, parent: 2, title: "test4" },
];
// This result array will contain all root objects,
// e.g. those with `parent === null`
const roots = [];
for (const object of objects) {
if (object.parent === null) {
roots.push(object);
}
else {
const parent = objects.find(o => o.id === object.parent);
if (parent) {
(parent.sub ||= []).push(object);
}
}
}
console.log(JSON.stringify(roots, null, 2));