0

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: []
 }]
 }]
}];
asked Feb 4, 2020 at 5:12
0

2 Answers 2

9

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.