获取到的data数组,包含所有树状结构的数据, data里的数据项是对象。
对象中有pId, 为父级的id。
通过pId找父级元素。
function setTree(data) {
data.forEach(function (item) {
elete item.children;// 删除 所有 children,以防止多次调用
});
// 将数据存储为 以 id 为 KEY 的 map 索引数据列
var map = {};
data.forEach(function (item) {
map[item.id] = item;
});
var val = [];
data.forEach(function (item) {
var parent = map[item.pId];
if (parent) {
(parent.children || (parent.children = [])).push(item);
} else {
val.push(item);
}
});
return val;
}