const srcTree = [ // 源数据
{
id: 1,
name: '测试 1',
children: [
{
id: 11,
name: '测试 1-1'
}
]
}
]
const distTree = [ // 结果
{
value: 1,
valuePath: [1],
name: '测试 1',
children: [
{
value: 11,
valuePath: [1, 11],
name: '测试 1-1'
}
]
}
]
//我自己写的,难点在于如何拿到上层节点的路径,不会问了AI才解决
//难点思路:在递归时“携带父路径”往下传递。当前节点的 valuePath=父路径parentPath+当前 id
function handleTree(src, parentPath = []) {
debugger
let obj = src[0]
let distTree = [];
let distObj = {}
distObj.value = obj.id
distObj.name = obj.name
distObj.valuePath=[...parentPath, obj.id];
if(Array.isArray(obj.children)&&obj.children.length>0){
distObj.children=handleTree(obj.children,distObj.valuePath)
}
distTree.push(distObj);
return distTree
}
console.log(JSON.stringify(handleTree(srcTree), null, 2));
//以下是AI给的答案
function mapTree(nodes, parentPath = []) {
return nodes.map((node) => {
const valuePath = [...parentPath, node.id];
const mapped = {
value: node.id,
name: node.name,
valuePath,
};
if (Array.isArray(node.children) && node.children.length > 0) {
mapped.children = mapTree(node.children, valuePath);
}
return mapped;
});
}
console