一个树形结构的数组对象,替换对象中的name换成txt,个人写法,如果有问题,欢迎指出!!!
直接上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let objAry = [{
id: 1,
name: 'zs',
children: [{
id: 101,
name: 'zs01',
children: []
}]
},
{
id: 2,
name: 'ls',
children: [{
id: 201,
name: 'ls01',
children: []
},
{
id: 202,
name: 'ls02',
children: [{
id: 2021,
name: 'ls021',
children: []
},
{
id: 2022,
name: 'ls022',
children: []
},
]
},
]
},
]
console.log('处理前', objAry)
function changeObjaryKey(objAry, key, newkey) {
objAry.forEach(item => {
// 新增替换的属性的键值
Object.assign(item, {
[newkey]: item[key]
})
// 去掉旧属性键值
delete item[key]
changeObjaryKey(item.children, key, newkey)
});
}
changeObjaryKey(objAry, 'name', 'txt')
// changeObjaryKey(objAry, 'id', 'ids')
console.log('处理后', objAry)
</script>
</body>
</html>