将数组arr处理成下面的结构
// parentdId为0的都是一级,二级的parentId等于一级的id
let arr = [
{
id: 1,
menuName: "并列的一级(1)",
parentId: 0,
children: [],
},
{
id: 10,
menuName: "(1)的下一级",
parentId: 1,
children: [],
},
{
id: 100,
menuName: "(1)的下一级的下一级",
parentId: 10,
children: [],
},
{
id: 2,
menuName: "并列的一级(2)",
parentId: 0,
children: [],
},
{
id: 20,
menuName: "(2)的下一级",
parentId: 2,
children: [],
}
]
function handleTree(data, id, parentId, children) {
let config = {
id: id || 'id',
parentId: parentId || 'parentId',
childrenList: children || 'children'
};
console.log(data);
var childrenListMap = {};
var nodeIds = {};
var tree = [];
for (let d of data) {
let parentId = d[config.parentId];
if (childrenListMap[parentId] == null) {
childrenListMap[parentId] = [];
}
nodeIds[d[config.id]] = d;
childrenListMap[parentId].push(d);
}
console.log(nodeIds); // 是一个对象 属性是menuId 属性值是menuId等于属性的对象
console.log(childrenListMap); // 是一个对象 属性是parentId 属性值是一个数组,里面是所有parentId等于属性的对象
for (let d of data) {
let parentId = d[config.parentId];
if (nodeIds[parentId] == null) { // 找所有的一级数组
tree.push(d);
}
}
console.log(tree); // 所有一级数组在所的数组
for (let t of tree) {
adaptToChildrenList(t);
}
function adaptToChildrenList(o) {
if (childrenListMap[o[config.id]] !== null) { // 如果childrenListMap里有属性和o的menuId一样的,就把他们放在o的children数组里
o[config.childrenList] = childrenListMap[o[config.id]];
}
if (o[config.childrenList]) { // 如果o的children存在就继续循环数组里的对象然后调用adaptToChildrenList
for (let c of o[config.childrenList]) {
adaptToChildrenList(c);
}
}
}
return tree;
}
var treeArr = handleTree(arr, 'id')
console.log(treeArr); // 处理完的数组