Javascript 扁平结构数组转树形结构
function transformTozTreeFormat(nodes) {
let i, l;
if (!nodes) return [];
if (Object.prototype.toString.call(nodes) == "[object Array]") {
let r = [];
let tmpMap = {};
for (i = 0, l = nodes.length; i < l; i++) {
tmpMap[nodes[i].id] = nodes[i];
}
for (i = 0, l = nodes.length; i < l; i++) {
let p = tmpMap[nodes[i].parentId];
if (p && nodes[i].id != nodes[i].parentId) {
if (!p.children) {
p.children = [];
}
p.children.push(nodes[i]);
} else {
r.push(nodes[i]);
}
}
return r;
} else {
return [nodes];
}
}
参考
ztree.core