This is the given array:
array = [{number : 1 , name : 'one' , child : [] },{number : 2, name : 'two' , child : []},{number : 3 , name : 'three' , child : []}]
How to create nested child objects in JavaScript from this array?
nested = [
{
number : 1,
name : 'one',
child : [
{
number : 2,
name : 'two',
child : [{
number : 3,
name : 'three',
child : []
}
]
}
]
}
]
i try to solve this but i cant do this
You can use recursion to solve this problem.
Here’s how you can do it:
const nested = array.reduceRight((a, b) => ({
...b,
child: [{...a}]
})
)
I hope this answer can help you even a little.
You can use the array.reduceRight
method to achieve your result.
Here’s how you can do it:
const array = [
{ number: 1, name: 'one', child: [] },
{ number: 2, name: 'two', child: [] },
{ number: 3, name: 'three', child: [] }
];
const nested = array.reduceRight((a, b) => {
b.child.push(a);
return b;
});
console.log(JSON.stringify(nested, null, 2));
JSON.stringify() The third argument enables pretty printing and sets the spacing