This is the given array:
[{
key: 1,
nodes: {}
}, {
key: 2,
nodes: {}
}, {
key: 3,
nodes: {}
}]
How to create nested child objects in JavaScript from this array?
[{
key: 1,
nodes: [{
key: 2,
nodes: [{
key: 3,
nodes: []
}]
}]
}];
Danny Fardy Jhonston Bermúdez
5,5915 gold badges27 silver badges38 bronze badges
2 Answers 2
This is a pretty good use case for reduceRight which allows you to build the structure from the inside out:
let arr = [{
key: 1,
nodes: {}
}, {
key: 2,
nodes: {}
}, {
key: 3,
nodes: {}
}]
let a = arr.reduceRight((arr, {key}) => [{key, nodes: arr}],[])
console.log(a)
answered Feb 4, 2020 at 5:24
Mark
92.7k8 gold badges116 silver badges156 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
It's working fine. Try this below code
const firstArray = [{ key: 1, nodes: {} }, { key: 2, nodes: {} }, { key: 3, nodes: {} }];
firstArray.reverse();
const nestedObject = firstArray.reduce((prev, current) => {
return {
...current,
nodes:[{...prev}]
}
}, {});
console.log(nestedObject)
answered Feb 4, 2020 at 6:38
Senthil
7672 gold badges7 silver badges25 bronze badges
Comments
lang-js