gpt4 book ai didi

javascript - 如何递归替换对象中的键名?

转载 作者:行者123 更新时间:2023-12-01 16:09:53 24 4
gpt4 key购买 nike

我正在尝试弄清楚如何使用递归将对象的键名替换为新的键名(这也包括嵌套对象内的键名)。我觉得这与我在第一个 if 条件语句中重新分配给 newObj 的方式有关。有什么建议么?到目前为止,这是我的代码:

// 24. Find all keys in an object (and nested objects) by a provided name and rename
// them to a provided new name while preserving the value stored at that key.

const replaceKeysInObj = (obj, oldKey, newKey, newObj = {}) => {
for(let key in obj){
if (key === oldKey){
newObj[newKey] = obj[key]
}
if (typeof obj[key] === 'object'){
replaceKeysInObj(obj[key], oldKey, newKey);
}
else {
newObj[oldKey] = obj[key]
}
}
return newObj
}


var obj = {'e':{'e':'y'},'l': 'l','y':'e'};
console.log(replaceKeysInObj(obj, 'e', 'new'))

最佳答案

对您的方法进行一些修改

const replaceKeysInObj = (obj, oldKey, newKey, newObj = {}) => {
if (typeof obj !== "object") return obj;
for (let key in obj) {
newObj[key === oldKey ? newKey : key] = replaceKeysInObj(obj[key], oldKey, newKey);
}
return newObj;
};

const obj = { e: { e: "y" }, l: "l", y: "e" };
console.log(replaceKeysInObj(obj, "e", "new"));

const obj2 = { e: { e: "y" }, l: { e: "y" }, y: "e" };
console.log(replaceKeysInObj(obj2, "e", "new"));

关于javascript - 如何递归替换对象中的键名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63109471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com