繁体   English   中英

更改对象基于结构的条件

[英]change object Structure based condition

我有一个类似下面的对象,

我正在尝试基于父子关系改革对象结构。

var b = [];
for(var i=0;i<a.length;i++){
if(a[i].parent == null){
const children = a.filter(x => a[i].parent == null && a[i].id == x.parent);
b.push({'name':a[i].name,'type':'grandparent','children':children})
}

}

我封存了祖父母和子女,但被困在子子女中。

您可以使用reduce()方法并为此创建递归函数。

 var a = [{"id":0,"name":"Node 0","thumbnail":{"description":"Random Picture","href":""},"parent":null},{"id":1,"name":"Node 1","thumbnail":{"description":"Another Random Picture","href":""},"parent":0},{"id":2,"name":"Node 2","thumbnail":{"description":"A Picture Is Random","href":""},"parent":null},{"id":3,"name":"Node 3","thumbnail":{"description":"Picture, Random","href":""},"parent":1}] function nested(arr, parentId) { return arr.reduce(function(r, e) { if (e.parent == parentId) { const children = nested(arr, e.id); const clone = Object.assign({}, e); if (children.length) clone.children = children r.push(clone) } return r; }, []) } const result = nested(a); console.log(result) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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