js树形数据结构和扁平数据互转

扁平转树形
toTree: function(data) {
data.forEach(function(ele) {
let pid = ele.pid;
ele.isEdit = false;
if (!ele.children) { //很多都有bug的,少了这个校验
ele.children = [];
}
if (pid == 0) {
//是根元素的hua ,不做任何操作,如果是正常的for-i循环,可以直接continue.
} else {
//如果ele是子元素的话 ,把ele扔到他的父亲的child数组中.
data.forEach(function(d) {
if (d.id == pid) {
let childArray = d.children;
if (!childArray) {
childArray = [];
}
childArray.push(ele);
d.children = childArray;
}
});
}
});
var result = [];
for (let i = 0; i < data.length; i++) {
var ele = data[i];
if (ele.pid == 0) {
result.push(ele);
}

            }
            return result;
        },

//获取树结构扁平
//arr扁平列表 result
getTreeList: function(arr, result) {
var self = this;
arr.forEach(function(item) {
if (item.children) {
result.push({ id: item.id, name: item.name, Grade: item.Grade, pid: item.pid });
self.getTreeList(item.children, result)
} else {
result.push({ id: item.id, name: item.name, Grade: item.Grade, pid: item.pid });
}
})
console.log(result);
},

你可能感兴趣的:(javaScript,树形与扁平互转,前端)