繁体   English   中英

如何组织类别集合?

[英]How can I organize a collection of categories?

我有一个包含所有孩子的类别集合,这些类别是我通过 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},

]

首先建立一张父母给孩子的地图:

 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);       
   }
 }

暂无
暂无

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

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