json数据转换,如何将扁平化数组转为树形结构?
如何将扁平化的数组转成树形结构,比如: const a = [[1,2,3],['a','b','c'],['A','B','C']]; 要求a数组转化后结果,如:
[
{
label: '1',
children:
[
{ label: 'a',
children:[
{
label:'A'
}
]
}
]
},
{
label: '2',
children:
[
{ label: 'b',
children:[
{
label:'B'
}
]
}
]
},
{
label: '3',
children:
[
{ label: 'c',
children:[
{
label:'C'
}
]
}
]
},
]
实现代码
var a = [
['111', '222', '3333'],
['xxx', 'qqq', 'abcd'],
['xxx', 'qqq', 'abcd'],
['xxx', 'qqq', 'abcd'],
['xxx', 'qqq', 'abcd']
];
var res = [];
for (let i = 0; i < a[0].length; i += 1) {
const obj = {}
let el = obj
for (let j = 0; j < a.length; j += 1) {
if (j === 0 ) {
el.label = a[j][i]
el.children = []
} else {
el.children.push({
label: a[j][i],
children: []
})
el = el.children[0]
}
}
res.push(obj)
}
console.log(res)