簡體   English   中英

如何從數組中創建 JavaScript 中的嵌套子對象?

[英]How to create nested child objects in JavaScript from array?

這是給定的數組:

[{
  key: 1,
  nodes: {}
}, {
  key: 2,
  nodes: {}
}, {
  key: 3,
  nodes: {}
}]

如何從該數組創建 JavaScript 中的嵌套子對象?

[{
  key: 1,
  nodes: [{
    key: 2,
    nodes: [{
      key: 3,
      nodes: []
    }]
  }]
}];

這是reduceRight的一個很好的用例,它允許您從內到外構建結構:

 let arr = [{ key: 1, nodes: {} }, { key: 2, nodes: {} }, { key: 3, nodes: {} }] let a = arr.reduceRight((arr, {key}) => [{key, nodes: arr}],[]) console.log(a)

它工作正常。 試試下面的代碼

  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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM