我有一个包含所有孩子的类别集合,我通过ajax从服务器获取。 现在我想以每个子类别都在相关父级下的方式对它们进行排序。
这是所有类别集合:
[
{id: 28, name: "category1", parent_id: null},
{id: 29, name: "category2", parent_id: null},
{id: 30, name: "category3", parent_id: null},
{id: 31, name: "category4", parent_id: 28},
{id: 32, name: "category5", parent_id: 28},
{id: 33, name: "category6", parent_id: 28},
{id: 34, name: "category7", parent_id: 31},
{id: 35, name: "category8", parent_id: 31},
{id: 36, name: "category9", parent_id: 29},
]
parent_id : null
表示它是父类别,而parent_id
的任何其他数字都指向父类别。
反正
我想用这样的数据创建一个集合:
[
{id: 28, name: "category1", parent_id: null,
children : [
{id: 31, name: "category4", parent_id: 28, [
children : [
{id: 34, name: "category7", parent_id: 31},
{id: 35, name: "category8", parent_id: 31},
]},
{id: 32, name: "category5", parent_id: 28},
{id: 33, name: "category6", parent_id: 28},
]},
{id: 29, name: "category2", parent_id: null,
children: [
{id: 36, name: "category9", parent_id: 29},
]},
{id: 30, name: "category3", parent_id: null},
]
答案 0 :(得分:1)
首先建立一个父母给孩子的地图:
const parentChilds = new Map;
for(const el of data){
const pid = el.parent_id;
if(parentChilds.has(pid)){
parentChilds.get(pid).push(el);
} else {
parentChilds.set(pid, [el]);
}
}
现在我们只需要将子数组存储在父对象中:
for(const el of data)
el.children = parentChilds.get(el.id) || [];
要仅获取顶级元素,只需过滤那些没有父级的元素:
const result = data.filter(el => !el.parent_id);
你实际上可以在一个循环中完成所有这些:
const parentChilds = new Map;
const result = [];
for(const el of data){
const {id, parent_id: pid} = el;
if(parentChilds.has(id)) {
el.children = parentChilds.get(id);
} else {
parentChilds.set(id, el.children = []);
}
if(pid){
if(parentChilds.has(pid)){
parentChilds.get(pid).push(el);
} else {
parenChilds.set(pid, [el]);
}
} else {
result.push(el);
}
}