简体   繁体   中英

How to create nested child objects in JavaScript from array?

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

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM