const menuData = [
{
id: 1,
label: '一级 1',
parent_catalog_id: '0'
}, {
id: 4,
parent_catalog_id: '1',
label: '二级 1-1'
}, {
id: 9,
parent_catalog_id: '4',
label: '三级 1-1-1'
}, {
id: 10,
parent_catalog_id: '4',
label: '三级 1-1-2'
}, {
id: 2,
label: '一级 2',
parent_catalog_id: '0'
}, {
id: 5,
parent_catalog_id: '2',
label: '二级 2-1'
}, {
id: 6,
parent_catalog_id: '2',
label: '二级 2-2'
}, {
id: 3,
label: '一级 3',
parent_catalog_id: '0'
}, {
id: 7,
parent_catalog_id: '3',
label: '二级 3-1'
}, {
id: 8,
parent_catalog_id: '3',
label: '二级 3-2'
}, {
id: 11,
label: '三级 3-2-1',
parent_catalog_id: '8',
}, {
id: 12,
parent_catalog_id: '8',
label: '三级 3-2-2'
}, {
id: 13,
parent_catalog_id: '8',
label: '三级 3-2-3'
}],
const arr = this.menuData;
let fatherList = [];
let fatherId = [];
let childList = [];
let childParentList = [];
arr.forEach(element => {
if (element.parent_catalog_id == '0') {
fatherList.push(element);
fatherId.push(element.id);
} else {
childList.push(element);
childParentList.push(parseInt(element.parent_catalog_id));
}
});
let drr = this.traversalTree(fatherId, fatherList, childList, childParentList);
traversalTree(fatherId, fatherList, childList, childParentList) {
let subFatherList = [];
let subFatherId = [];
let subChildList = [];
let subChildParentList = [];
childParentList.forEach((item, index) => {
const num = fatherId.indexOf(item);
if (num > -1) {
if (!(fatherList[num].children && fatherList[num].children.length > 0)) {
fatherList[num].children = [];
}
fatherList[num].children.push(childList[index]);
subFatherList.push(childList[index]);
subFatherId.push(childList[index].id);
} else {
subChildList.push(childList[index]);
subChildParentList.push(parseInt(childList[index].parent_catalog_id));
}
});
if (subChildList.length > 0) {
let resultChildArr = this.traversalTree(subFatherId, subFatherList, subChildList, subChildParentList);
resultChildArr.forEach((item, index) => {
const num = fatherId.indexOf(parseInt(item.parent_catalog_id));
fatherList[num].children.some((element, inx) => {
if (item.id == element.id) {
fatherList[num].children[inx] = item;
return true;
}
});
});
}
return fatherList;
}