【发布时间】:2021-10-20 18:40:39
【问题描述】:
您好,我想从类别列表中获取子树。
这是我的输入数据
[
{ "parent_id": -1, "name": "Toothpaste", "id": 99 },
{
"parent_id": -1,
"name": "Cake",
"id": 3
},
{
"parent_id": 3,
"name": "Chocolate Cake",
"id": 4
},
{
"parent_id": 3,
"name": "Walnut Cake",
"id": 5
},
{
"parent_id": 4,
"name": "Chocolate Cake mixin 1",
"id": 6
}
]
我想要的输出如下图所示
[ { "parent_id": -1, "name": "Toothpaste", "id": 99 },
{
"parent_id": -1,
"name": "Cake",
"id": 3,
"children":[
{
"parent_id": 3,
"name": "Chocolate Cake",
"id": 4,
"children":[ //<--- observe this one not there in my output
{
"parent_id": 4,
"name": "Chocolate Cake mixin 1",
"id": 6
}
]
},
{
"parent_id": 3,
"name": "Walnut Cake",
"id": 5
}
],
}
]
我面临的问题是我无法将数据推送到第二级,即巧克力蛋糕正在生孩子,但我无法将其推送到巧克力蛋糕儿童中 p>
注意:解决方案必须适用于任何级别的嵌套
这是我尝试过的
function getChildrenTree(childList){
let childMap = {};
for(let i = 0; i < childList.length; i++){
if(childList[i].parent_id === -1)
childMap[childList[i].id] = {name:childList[i].name,children:[]};
}
for(let i = 0; i < childList.length; i++){
if(childMap && childMap.hasOwnProperty(childList[i].parent_id) && childMap[childList[i].parent_id].hasOwnProperty('children')) childMap[childList[i].parent_id].children.push(childList[i]);
}
return Object.values(childMap);
}
getChildrenTree([ { "parent_id": -1, "name": "Toothpaste", "id": 99 },{ "parent_id": -1, "name": "Cake", "id": 3 }, { "parent_id": 3, "name": "Chocolate Cake", "id": 4 }, { "parent_id": 3, "name": "Walnut Cake", "id": 5 }, { "parent_id": 4, "name": "Chocolate Cake mixin 1", "id": 6 } ])
【问题讨论】:
-
不是因为在我的情况下我可以有多个一级父级
parent_id = -1 -
在我的代码中 sn-p
toothpaste是一级父级之一 -
@James 在我的情况下,一级父母将始终拥有
id=-1,否则它不是父母。在上面的评论中我犯了一个错误,而不是id我把parent_id.
标签: javascript jquery tree