【发布时间】:2019-10-24 03:23:32
【问题描述】:
我有一个这样的对象,
{
id: '1',
displaName: 'A',
children: [
{
id: '2',
displayName: 'B',
children: [
{
id: '3',
displayName: 'C',
children: [
//More nested array here
]
}
]
}]
}
我只想将键 displayName 更改为 label,以便我的对象看起来像这样,
{
id: '1',
label: 'A', //change key displayName => label
children: [
{
id: '2',
label: 'B', //change key displayName => label
children: [
{
id: '3',
label: 'C', //change key displayName => label
children: [
//More nested array here
]
}
]
}]
}
我已经尝试过了,但无法替换嵌套数组中的键,
const newKeys = { displaName: "label"};
const renamedObj = renameKeys(resp.data, newKeys);
console.log(renamedObj);
function renameKeys(obj, newKeys) {
const keyValues = Object.keys(obj).map(key => {
console.log(key);
let newKey = null
if(key === 'displayName'){
newKey = 'label'
}else{
newKey = key
}
console.log(newKey);
return { [newKey]: obj[key] };
});
return Object.assign({}, ...keyValues);
}
请帮我解决这个问题。
提前致谢。
【问题讨论】:
标签: javascript javascript-objects