原始数据
let res = [
{
indexCode: 'root00',
name: '总区域',
parentIndexCode: '-1',
},
{
indexCode: 'A-01',
name: 'A区域-01',
parentIndexCode: 'root00',
},
{
indexCode: 'B-01',
name: 'B区域-01',
parentIndexCode: 'root00',
},
{
indexCode: 'A-01-01',
name: 'A区域-01-01',
parentIndexCode: 'A-01',
},
{
indexCode: 'A-01-02',
name: 'A区域-01-02',
parentIndexCode: 'A-01',
},
{
indexCode: 'A-01-01-01',
name: 'A区域-01-01-01',
parentIndexCode: 'A-01-01',
},
];
递归函数
function createTree(arr, parentIndex) {
let treeData = [];
arr.forEach(item => {
if (parentIndex == item.parentIndexCode) {
item.children = createTree(arr, item.indexCode);
treeData.push(item);
}
});
return treeData;
};
递归结果
let data = createTree(res, 'root00');
console.log(data);
[
{
indexCode: "A-01",
name: "A区域-01",
parentIndexCode: "root00",
children: [
{
indexCode: "A-01-01",
name: "A区域-01-01",
parentIndexCode: "A-01",
children: [
{
indexCode: "A-01-01-01",
name: "A区域-01-01-01",
parentIndexCode: "A-01-01",
children: []
}
]
},
{
indexCode: "A-01-02",
name: "A区域-01-02",
parentIndexCode: "A-01",
children: []
}
]
},
{
indexCode: "B-01",
name: "B区域-01",
parentIndexCode: "root00",
children: []
}
]