首页 > 解决方案 > 如何递归替换对象中的键名?

问题描述

我试图弄清楚如何使用递归将对象的键名替换为新的键名(这也包括嵌套对象内的键名)。我觉得这与我在第一个 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')) 

标签: javascriptrecursion

解决方案


对您的方法进行一些修改

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"));


推荐阅读