javascript - 如何替换嵌套对象中的键
问题描述
我有一个这样的对象,
{
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);
}
请帮我解决这个问题。
提前致谢。
解决方案
您的代码中有错字。一些变量显示为
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);
}
推荐阅读
- sharepoint - 在 SPfx 应用程序中获取用户事件的 Microsoft GraphAPI 403 错误
- python - 循环遍历 pandas 数据框列中的列表元素以在新列中返回列表
- angular - 在 ng 服务中找不到模块“@angular/compiler-cli/ngcc”
- r - R commandArgs() 抑制有关参数被忽略的警告
- xml - xmlstarlet 提取以不同值重复的子 HTML 元素的值
- dimension - 继续训练预训练数据时的维度问题
- python - 查找变量的物理内存地址?
- r - 通货膨胀率的时间序列
- javascript - 由于 javascript 是 Ecmascript 的实现,那么这个实现称为“javascript”的规范是什么?
- python - 如何将返回值分配给 __init__ 值