tree转list:
treeToList(datas){
var arr = [];
formateData(datas,0);
function formateData(datas,level){
var level = level || 0;
level ++;
for(var i in datas){
arr.push({id:datas[i]['id'],orgNodeName:datas[i]['名字'],name:datas[i]['name'],level:level,value:datas[i]['value'],});
if(datas[i].children){
formateData(datas[i].children,level);
}
}
}
return arr;
},
list转tree:
例:
test() {
const list = [
{ id: 1, name: 'a' },
{ id: 11, name: 'aa', pid: 1 },
{ id: 12, name: 'aaa', pid: 1 },
{ id: 13, name: 'aaaa', pid: 1 },
{ id: 2, name: 'b' },
{ id: 22, name: 'bb', pid: 2 },
{ id: 23, name: 'bbb', pid: 2 },
{ id: 24, name: 'bbbb', pid: 2 },
{ id: 3, name: 'c' },
{ id: 31, name: 'cc', pid: 3 },
{ id: 32, name: 'ccc', pid: 3 },
{ id: 33, name: 'cccc', pid: 3 },
{ id: 111, name: 'a11', pid: 11 },
{ id: 112, name: 'aa11', pid: 11 },
{ id: 1121, name: 'aa112', pid: 112 }
];
//prev 是我们最终要生成的树型机构
//curr 为当前的数据
//i为索引
//arr为我们整个list
const result = list.reduce(function (prev, curr, i, arr) {
curr.children = arr.filter((v) => v.pid === curr.id);
if (!curr.pid) {
prev.push(curr);
}
return prev;
}, []);
console.log('list', list);
console.log('tree', result);
},