在使用element-ui的el-tree,由于后端返回的是一个常规数组,于是便手撸了一个数组转数的方法。留存于此,以便日后方便。
代码如下:
后端返回的数据:
let arrData = [
{id: 1, name: '1', parentId: null},
{id: 2, name: '2', parentId: null},
{id: 3, name: '1-1', parentId: 1},
{id: 4, name: '1-2', parentId: 1},
{id: 5, name: '2-1', parentId: 2},
{id: 6, name: '2-2', parentId: 2},
{id: 7, name: '1-1-1', parentId: 3},
{id: 8, name: '1-2-1', parentId: 4},
{id: 9, name: '1-2-2', parentId: 4},
{id: 10, name: '2-1-1', parentId: 5},
{id: 11, name: '2-2-1', parentId: 6},
]
/*
传参:
arg1: Array, 原数组
arg2:{ // 默认字段名
id: 'id',
parentId: 'parentId',
children : 'children',
initialVal: null // 默认一级菜单的parentId值
}
*/
function arrayToTree(array,propNames = {}) {
let {
_id = 'id',
parentId = 'parentId',
children = 'children',
initialVal = null
} = propNames;
return loopArr(array,_id,parentId,children,initialVal);
}
function loopArr(array,_id,parentId,children,initialVal) {
let arr = array.filter(item => item[parentId] === initialVal);
let arr1 = array.filter(item => item[parentId] !== initialVal);
if(arr.length && arr1.length) {
arr = arr.map(item => {
item[children] = loopArr(arr1,_id,parentId,children,item[_id])
return item;
})
}
return arr;
}
console.log(arrayToTree(arrData)) //调用方法