vuejs处理树状结构的数据扁平化

1,有这样一个数据:

复制代码
 1 data = [
 2         {
 3             "id":1,
 4             "name":"吃喝",
 5             "parentId":0,
 6             "children":[
 7                 {
 8                     "id":2,
 9                     "name":"烧烤",
10                     "parentId":"1",
11                     "children":[]
12                 },
13                 {
14                     "id":5,
15                     "name":"奶茶",
16                     "parentId":"1",
17                     "children":[]
18                 }
19             ]
20         },
21         {
22             "id":3,
23             "name":"玩乐",
24             "parentId":0,
25             "children":[
26                 {
27                     "id":4,
28                     "name":"ktv",
29                     "parentId":"3",
30                     "children":[]
31                 },
32                 {
33                     "id":6,
34                     "name":"棋牌室",
35                     "parentId":"3",
36                     "children":[]
37                 }
38             ]
39         }
40     ]
复制代码

2,使用函数进行数据扁平化

复制代码
 1  /**
 2     *
 3     * @param {Array} arrs 树形数据
 4     * @param {string} childs 树形数据子数据的属性名,常用'children'
 5     * @param {Array} attrArr 需要提取的公共属性数组(默认是除了childs的全部属性)(可不写)
 6     * @returns
 7     */
 8    function extractTree(arrs,childs,attrArr){
 9        let attrList = [];
10        if(!Array.isArray(arrs)&&!arrs.length)return [];
11        if(typeof childs !== 'string')return [];
12        if(!Array.isArray(attrArr)||Array.isArray(attrArr)&&!attrArr.length) {
13               attrList = Object.keys(arrs[0]);
14               attrList.splice(attrList.indexOf(childs), 1);
15          }else{
16               attrList = attrArr;
17          }
18         let list = [];
19         const getObj = (arr)=>{
20            arr.forEach(function(row){
21                let obj = {};
22                attrList.forEach(item=>{
23                   obj[item] = row[item];
24         });
25          list.push(obj);
26          if(row[childs]){
27              getObj(row[childs]);
28          }
29         })
30         return list;
31       }
32      return getObj(arrs);
33   }
复制代码

 

posted @   程序员肉包子  阅读(935)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示