gpt4 book ai didi

javascript - 在深度级别的基础上链接 child 和 parent

转载 作者:行者123 更新时间:2023-12-05 09:10:30 25 4
gpt4 key购买 nike

我的所有父子都在一个数组数据中。我想要的是在每个对象上添加一个新属性(级别)。

假设我有数据

 var data = [
{
id: 1,
parent_id: 0,
name: "Child1",
},
{
id: 4,
parent_id: 1,
name: "Child11",

},

{
id: 5,
parent_id: 4,
name: "Child111",
},
{
id: 11,
parent_id: 4,
name: "Child112"
},


{
id: 13,
parent_id: 11,
name: "Child1121",
},

{
id: 21,
parent_id: 11,
name: "Child1122"
},
{
id: 22,
parent_id: 11,
name: "Child1123"
},
{
id: 24,
parent_id: 1,
name: 'Child12'
}

]

我想要一个基于 child 的 parent_idchild-parent 关系,并在数组的每个对象中分配一个新属性作为表示深度级别的级别 child 基于其 parent 。我的预期结果是:

var data = [
{
id: 1,
parent_id: 0, <-------represents root
name: "Child1",
level:0 <--------level based on its parent_id
},
{
id: 4,
parent_id: 1
name: "Child11",
level:1

},
{
id: 5,
parent_id: 4,
name: "Child111",
level:2
},
{
id: 11,
parent_id: 4,
name: "Child112",
level:2
},


{
id: 13,
parent_id: 11,
name: "Child1121",
level:3
},

{
id: 21,
parent_id: 11,
name: "Child1122",
level:3
},
{
id: 22,
parent_id: 11,
name: "Child1123",
level:3
},
{
id: 24,
parent_id: 1,
name: 'Child12',
level:1
}

]


我的代码


function buildTree(elements, parent_id, level = 0) {

elements.forEach(element => {


if (element['parent_id'] == parent_id) {
console.log('parent_id', parent_id);
// elements.filter(item=>item!==element);
element['level'] = level;

}
else{
buildTree(elements,parent_id,level+1);
}





})




return elements;




}



最佳答案

对于已排序的数据,您可以为级别计数取一个对象并映射一个新的数据集。

var data = [{ id: 1, parent_id: 0, name: "Child1" }, { id: 4, parent_id: 1, name: "Child11" }, { id: 5, parent_id: 4, name: "Child111" }, { id: 11, parent_id: 4, name: "Child112" }, { id: 13, parent_id: 11, name: "Child1121" }, { id: 21, parent_id: 11, name: "Child1122" }, { id: 22, parent_id: 11, name: "Child1123" }, { id: 24, parent_id: 1, name: 'Child12' }],
levels = {},
result = data.map(o => ({
...o,
level: levels[o.id] = o.parent_id in levels
? levels[o.parent_id] + 1
: 0
}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 在深度级别的基础上链接 child 和 parent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61382030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com