<body>
<script>
let tree = [
{
id: '1',
title: '节点1',
children: [
{
id: '1-1',
title: '节点1-1'
},
{
id: '1-2',
title: '节点1-2'
}
]
},
{
id: '2',
title: '节点2',
children: [
{
id: '2-1',
title: '节点2-1',
children: [
{
id: '3-1',
title: '节点3-1'
}
]
}
]
}
]
let newTree = []
handleTree(newTree, tree)
console.log(newTree);
function handleTree(newTree, oldTree) {
for (let i = 0; i < oldTree.length; i++) {
newTree[i] = {}
for (const key in oldTree[i]) {
if (Object.hasOwnProperty.call(oldTree[i], key)) {
// 有children的做递归处理
if (key === 'children' && oldTree[i].children.length > 0) {
newTree[i][key + 's'] = []
handleTree(newTree[i][key + 's'], oldTree[i].children)
// 没有children的修改key值,修改为自己需要的key
} else {
const element = oldTree[i][key]
if (key === 'id') {
newTree[i]['value'] = element
// console.log(newTree[i]);
} else if (key === 'title') {
newTree[i]['lable'] = element
} else if (key === 'children') {
newTree[i]['childrens'] = element
}
}
}
}
}
}
</script>
</body>
部分结果展示:key已修改
