设后端通过接口返回了天猫的行业信息

let industry_list = [{
name: '女装'
},
{
parent_ind: '女装',
name: '连衣裙'
},
{
parent_ind: '女装',
name: '半身群'
},
{
parent_ind: '女装',
name: 'A字群'
},
{
name: '数码'
},
{
parent_ind: '数码',
name: '电脑配件'
},
{
parent_ind: '电脑配件',
name: '内存'
}
];

可以将其转换为树状格式

{
'女装':{
'连衣裙':{},
'半身群':{},
'A字群':{},
},
'数码':{
'电脑配件':{
'内存':{},
},
},
}

实现方法完成转换

function convert_format(data) {
// 取第一级
const tempRootList = data.filter((val) => !val.hasOwnProperty('parent_ind'))
// 取子级
const tempChildList = data.filter((val) => val.hasOwnProperty('parent_ind'))
const finalMap = {}
// 初始化
for (let item of tempRootList) {
finalMap[item.name] = {}
}
// 递归父级查找与父级Key相等的子集
function findParent(parentMap, childMap) {
for (let item of Object.keys(parentMap)) {
if (item === childMap.parent_ind) {
let tempName = childMap.name
parentMap[item][tempName] = {}
return
}
}
for (let item of Object.values(parentMap)) {
findParent(item, childMap)
}

}
// 遍历子集插入父级
for (let item of tempChildList) {
findParent(finalMap, item)
}

return finalMap
}

console.log(convert_format(industry_list));

通过接口向前端返回了天猫的行业信息,将其转换为树状格式-无限嵌套_转换为树状格式