[英]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.