工作项目中, 遇到一些数据转化格式的问题,特此记录一下:
1. 数组转化为具有层级关系的对象
需求: 如下图所示
实现思路: 先找出一级节点,然后对应父子级依赖关系进行遍历,递归。
具体实现方法如下:
// { 女装: { 连衣裙: {}, ... }, 数码: { 电脑配件: 内存 } }
const list = [
{ parent_ind: '女装', name: '连衣裙' },
{ name: '女装' },
{ parent_ind: '女装', name: '半身裙' },
{ parent_ind: '女装', name: 'A字裙' },
{ parent_ind: '连衣裙', name: '连衣裙红色' },
{ name: '数码' },
{ parent_ind: '数码', name: '电脑配件' },
{ parent_ind: '电脑配件', name: '内存' },
{ parent_ind: '内存', name: '内存卡' }
]
let newObj = formatArrayToObj(list)
console.log(newObj)
function formatArrayToObj(list) {
let obj = {};
// 一级父节点
let parentList = list.filter(item => !item.parent_ind)
// 除去一级父节点之外的节点
let childList = list.filter(item => item.parent_ind)
parentList.forEach(e => {
obj[e.name] = {};
})
childList.forEach(e => {
// 简化后方法
deepLoopJudgeChild(e, obj);
})
return obj
}
function deepLoopJudgeChild(e, obj) {
let deepLook = true;
for(let pId in obj) {
if (e.parent_ind === pId) {
obj[pId][e.name] = {};
deepLook = false;
}
}
if(deepLook) {
for(let pId in obj) {
deepLoopJudgeChild(e, obj[pId])
}
}
}