问题: 将后台返回的平级数据转换为嵌套数据格式
getTestData(){
const arr = this.testData // 请求到的源数据
const result = [];
for (let data of this.testData) {
if (data.parent_id == 0){ // 判断是否为顶层节点
var parent = {
"cate_id": data.cate_id,
"cate_name": data.cate_name,
"parent_id": data.parent_id,
"show_in_nav": data.show_in_nav,
"sort_order": data.sort_order,
"children": []
}
parent.children = this.getchilds(parent.cate_id, this.testData);
result.push(parent)
}
}
this.resultData = result //处理完成的数据赋值给data中定义的属性
},
getchilds(id, array) {
let childs = new Array();
for (let arr of array) {
if (arr.parent_id == id) {
childs.push({
"cate_id": arr.cate_id,
"cate_name": arr.cate_name,
"parent_id": arr.parent_id,
"show_in_nav": arr.show_in_nav,
"sort_order": arr.sort_order
})
}
}
for (let child of childs) {
let childscopy = this.getchilds(child.cate_id, array);
if (childscopy.length > 0) {
child.children = childscopy;
}
}
return childs;
}