js树形结构数据更改属性名
时间: 2023-11-30 13:05:51 浏览: 77
可以使用递归遍历树形结构数据,找到需要更改属性名的节点,然后修改其属性名。代码示例:
```javascript
function changePropertyName(node, oldName, newName) {
// 如果节点没有子节点,则直接修改属性名
if (!node.children) {
node[newName] = node[oldName];
delete node[oldName];
return;
}
// 如果节点有子节点,则递归遍历子节点
for (let child of node.children) {
changePropertyName(child, oldName, newName);
}
// 修改当前节点的属性名
node[newName] = node[oldName];
delete node[oldName];
}
let data = {
name: 'root',
children: [
{
name: 'child1',
children: [
{ name: 'grandchild1' },
{ name: 'grandchild2' }
]
},
{
name: 'child2',
children: [
{ name: 'grandchild3' },
{ name: 'grandchild4' }
]
}
]
};
changePropertyName(data, 'name', 'label');
console.log(data);
```
输出结果:
```
{
"label": "root",
"children": [
{
"label": "child1",
"children": [
{ "label": "grandchild1" },
{ "label": "grandchild2" }
]
},
{
"label": "child2",
"children": [
{ "label": "grandchild3" },
{ "label": "grandchild4" }
]
}
]
}
```
阅读全文