我们经常会遇到想处理扁平化数据,例如数据是这样的:
var json = '{"code":0,"parent":[{"name":"文件夹1","pid":0,"id":1},{"name":"文件夹2","pid":0,"id":2},{"name":"文件夹3","pid":0,"id":3},{"name":"文件夹1-1","pid":1,"id":4},{"name":"文件夹2-1","pid":2,"id":5}],"child":[{"name":"文件1","pid":1,"id":10001},{"name":"文件2","pid":1,"id":10002},{"name":"文件2-1","pid":2,"id":10003},{"name":"文件2-2","pid":2,"id":10004},{"name":"文件1-1-1","pid":4,"id":10005},{"name":"文件2-1-1","pid":5,"id":10006}]}';
目前测试过有效的方法有两种方法
第一种:(采用两层fiter)
data = JSON.parse(json);
var result = transformData(data);
console.log(result);
function transformData(data) {
let allData = JSON.parse(JSON.stringify(data));
var data_new = [...allData.parent,...allData.child];
console.log(data_new);
var result = data_new.filter(parent=>{
let findChildren = data_new.filter(child=>{
return parent.id === child.pid
})
if(findChildren.length>0) parent.children = findChildren;
// findChildren.length>0 ? parent.children = findChildren : parent.children = []
return parent.pid == 0 //返回顶层,依据实际情况判断这里的返回值
})
return result;
}
第二种:(采用reduce)
function transformData(data) {
let allData = JSON.parse(JSON.stringify(data));
var data_new = [...allData.parent,...allData.child];
let treeMapList = data_new.reduce((obj, current) => {
current.label = current.label || current.name;
obj[current["id"]] = current;
return obj;
}, {});
//看每个对象中pid值是否跟treeMapList中id的值相等,若相等就说是children中的数据
let result = data_new.reduce((arr, current) => {
let pid = current.pid;
let parent = treeMapList[pid]; //拿父亲的数据
if (parent) {
parent.children
? parent.children.push(current)
: (parent.children = [current]);
} else if (pid === 0) {
arr.push(current);
}
return arr;
}, []);
return result;
}