假设后端同学通过接口向前端返回了天猫的行业信息,例如:
industry_list = [
{
"parent_ind" : "女装",
"name" : "连衣裙"
},
{
"name": "女装"
},
{
"parent_ind" : "女装",
"name" : "半身裙"
},
{
"parent_ind" : "女装",
"name" : "A字裙"
},
{
"name": "数码"
},
{
"parent_ind" : "数码",
"name": "电脑配件"
},
{
"parent_ind" : "电脑配件",
"name": "内存"
},
]
为了取用方便,我们希望可以将其转换为树状格式,例如:
{
"数码": {
"电脑配件": {
"内存" : {}
}
},
"女装" : {
"连衣裙": {},
"半身裙": {},
"A字裙": {}
}
}
function convert_format(data) {
let map = new Map();
for (let i = 0; i < data.length; i++) {
let name = data[i].name;
map.set(name, map.get(name) || {});
// 父节点存入map
let parentId = data[i].parent_ind || "root";
let parent = map.get(parentId) || {};
// 为父节点添加当前节点
parent[name] = map.get(name);
map.set(parentId, parent);
}
return map.get("root");
}