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 }
标签:attrList,childs,扁平化,树状,vuejs,attrArr,parentId,children,name From: https://www.cnblogs.com/fxw1996/p/16992287.html