// 核心代码
// 第一个参数:接受数组,元素里面的children字段为子元素
// 第二个参数:元素里面没有children或children长度为0时,选取作为默认值的字段
function treeToObj(treeArr, defValField = undefined) {
let obj = {};
for (let i = 0; i < treeArr.length; i++) {
let node = treeArr[i];
if (node.children && node.children.length) {
obj[node.name] = treeToObj(node.children)
} else {
obj[node.name] = node.hasOwnProperty(defValField) ? node[defValField] : {}
}
}
return obj;
}
// 运行
let treeList = [
{
name: 'A',
value: 'deded',
children: [{
name: 'B',
value: 'bbbb',
children: [{
name: 'C',
value: 'cccc'
}]
}]
},
{
name: 'J',
value: 'deded'
},
{
name: 'K',
value: 123
},
{
name: 'Z',
value: {},
children: [{
name: 'Y',
value: {}
}]
},
]
console.log('treeToObj(treeList)', treeToObj(treeList))
网友评论