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: []
    }]
  }]
}];
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)

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)

Comments

Your Answer

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.