javascript - 如何递归替换对象中的键名?
问题描述
我试图弄清楚如何使用递归将对象的键名替换为新的键名(这也包括嵌套对象内的键名)。我觉得这与我在第一个 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 - React redux 无法正确调度
- gradle - Gradle onlyIf 任务条件不起作用
- ios - 如何防止 ERR_TIMEOUT 来自 Epson TM-m30 热敏行式打印机在使用 SDK for iOS 的打印进度中出现超时错误?
- laravel - 如何在 Laravel 中测试由服务创建的 cookie
- php - 用 php 创建特定的 json 结构
- nginx - Nginx proxy_pass 在变量中定义目标时改变行为
- javascript - HTML input type="file" onchange="form.submit()" 不适用于 Flask
- mysql - mysql二进制在性能上比char好?
- c++ - 从 bmp 图像打印像素数组
- python - 带索引的字典理解