[英]How can I organize a collection of categories?
I have a collection of categories with all their children which I get from the server via ajax.我有一个包含所有孩子的类别集合,这些类别是我通过 ajax 从服务器获得的。 Now I want to order them in a way that every child category go under the related parent.
现在我想以每个子类别都在相关父项下的方式对它们进行排序。
This is the all categories collection :这是所有类别的集合:
[
{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
means it's a parent category and any other number for the parent_id
is pointing to the category parent. parent_id : null
表示它是父类别,并且parent_id
任何其他数字都指向类别父级。
anyway反正
I want to create a collection out of that data like this :我想用这样的数据创建一个集合:
[
{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},
]
At first build up a Map of parents to their children:首先建立一张父母给孩子的地图:
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]);
}
}
Now we only need to store the children arrays in the parents:现在我们只需要将子数组存储在父数组中:
for(const el of data)
el.children = parentChilds.get(el.id) || [];
To get only the top level elements simply filter those without a parent:要仅获取顶级元素,只需过滤那些没有父元素的元素:
const result = data.filter(el => !el.parent_id);
You can actually do that all in one loop:您实际上可以在一个循环中完成所有操作:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.