Skip to content

Instantly share code, notes, and snippets.

@guoshuai93
Created December 30, 2024 03:05
Show Gist options
  • Save guoshuai93/07c0a89fdab99ec4c60d82afbcb332af to your computer and use it in GitHub Desktop.
Save guoshuai93/07c0a89fdab99ec4c60d82afbcb332af to your computer and use it in GitHub Desktop.
遍历树结构的数组,支持修改对象的属性,并返回新的数组
// 遍历树结构的数组,支持修改对象的属性,并返回新的数组
function traverseAndModifyTree(tree, modifyFn) {
function traverse(node) {
// 修改节点属性
const newNode = modifyFn(node);
// 递归遍历子节点
if (newNode.children) {
newNode.children = newNode.children.map(child => traverse(child));
}
return newNode;
}
return tree.map(node => traverse(node));
}
// 示例树结构
const tree = [
{
value: 1,
children: [
{
value: 2,
children: [
{ value: 4 },
{ value: 5 }
]
},
{ value: 3 }
]
}
];
// 示例修改函数
function modifyFn(node) {
return {
...node,
value: node.value * 2 // 将节点的值乘以2
};
}
const newTree = traverseAndModifyTree(tree, modifyFn);
console.log(newTree);
@guoshuai93
Copy link
Author

snow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment