/**
* 将普通数组转换为tree数组
* @param a 需要转换的普通数组,要转变为json字符串
* @param idStr 数组里的id,用来区别每个元素
* @param pidStr 元素对应的父元素的id值
* @param chindrenStr 父元素中子元素的名称
* @returns {[]}
*/
arrayToTree (a, idStr, pidStr, chindrenStr) {
const r = [];
const hash = {};
const id = idStr;
const pid = pidStr;
const children = chindrenStr;
let i = 0;
let j = 0;
const len = a.length;
for (; i < len; i++) {
hash[a[i][id]] = a[i];
}
for (; j < len; j++) {
const aVal = a[j];
const hashVP = hash[aVal[pid]];
if (hashVP) {
!hashVP[children] && (hashVP[children] = []);
hashVP[children].push(aVal);
} else {
r.push(aVal);
}
}
return r;
},
//调用方法示例:
this.myTreeData = this.arrayToTree(JSON.parse(JSON.stringify(res.data.rows)), 'Id', 'parentId', 'children')
el-tree使用时,将普通数组转换为tree数组
最新推荐文章于 2022-10-20 09:53:09 发布