将扁平化的数据结构,组装成为对象树结构
2018-12-29 本文已影响43人
cs0710
将扁平化的数据结构,组装成为对象树结构
const tempObj = {
h3: {
parent: 'h2',
name: '副总经理(市场)'
},
h1: {
parent: 'h0',
name: '公司机构'
},
h7: {
parent: 'h6',
name: '副总经理(总务)'
},
h4: {
parent: 'h3',
name: '销售经理'
},
h2: {
parent: 'h1',
name: '总经理'
},
h8: {
parent: 'h0',
name: '财务总监'
},
h6: {
parent: 'h4',
name: '仓管总监'
},
h5: {
parent: 'h4',
name: '销售代表'
},
h0: {
parent: '',
name: 'root'
}
}
进行对象遍历,找出对象key和子对象parent之间的关联
let finalObj = {}
for (const key in tempObj) {
const parent = tempObj[key].parent
if (!parent) {
finalObj = tempObj[key]
} else {
tempObj[parent][key] = tempObj[key]
}
}
console.log(finalObj);
