我有一个这样的对象,
{
id: '1',
displaName: 'A',
children: [
{
id: '2',
displayName: 'B',
children: [
{
id: '3',
displayName: 'C',
children: [
//More nested array here
]
}
]
}]
}
我只想用 label
更改键 displayName
以便我的对象看起来像这样,
{
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);
}
请帮我解决这个问题。
提前致谢。
最佳答案
您的代码中有拼写错误。一些变量显示为
displaName
而不是displayName
。您需要递归调用函数才能按预期工作。
您没有使用
newKeys
变量进行重命名。您只需将其硬编码为newKey = 'label'
。但这个问题与问题无关。
const resp = {
data: {
id: '1',
displayName: 'A',
children: [{
id: '2',
displayName: 'B',
children: [{
id: '3',
displayName: 'C',
children: [
//More nested array here
]
}]
}]
}
}
const newKeys = {
displayName: "label"
};
const renamedObj = this.renameKeys(resp.data, newKeys);
console.log(renamedObj);
function renameKeys(obj, newKeys) {
const keyValues = Object.keys(obj).map(key => {
let newKey = null
if (key === 'displayName') {
newKey = newKeys.displayName
} else {
newKey = key
}
if (key === 'children') {
obj[key] = obj[key].map(obj => renameKeys(obj, newKeys));
}
return {
[newKey]: obj[key]
};
});
return Object.assign({}, ...keyValues);
}
关于javascript - 如何替换嵌套对象中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58533695/