1.代码示例:
function replaceKey(obj, oldKey, newKey) {// 如果不是对象或者oldKey不存在,直接返回原对象if (typeof obj !== 'object' || !obj || !(oldKey in obj)) return obj;// 如果是数组,遍历数组每个元素if (Array.isArray(obj)) {obj.forEach((item, index) => {obj[index] = replaceKey(item, oldKey, newKey);});} else {// 如果oldKey在对象中,则替换键名if (oldKey in obj) {obj[newKey] = obj[oldKey];delete obj[oldKey];}// 遍历对象的其他属性,递归替换Object.keys(obj).forEach(key => {obj[key] = replaceKey(obj[key], oldKey, newKey);});}return obj;
}// 示例使用
const originalObject = {a: 1,b: { a: 2, b: { a: 3 } },c: [{ a: 4 }, { a: 5 }]
};const newObject = replaceKey(originalObject, 'a', 'x');
console.log(newObject);
2.输出结果