是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
当前回答
就我个人而言,重命名对象中的键而不实现额外的沉重插件和轮子的最有效的方法:
var str = JSON.stringify(object);
str = str.replace(/oldKey/g, 'newKey');
str = str.replace(/oldKey2/g, 'newKey2');
object = JSON.parse(str);
如果对象具有无效的结构,还可以将其封装在try-catch中。工作完美无缺:)
其他回答
我只想用ES6(ES2015)的方式!
我们需要跟上时代!
const old_obj = { k1: `111`, k2: `222`, k3: `333` }; console.log(`old_obj =\n`, old_obj); // {k1: "111", k2: "222", k3: "333"} /** * @author xgqfrms * @description ES6 ...spread & Destructuring Assignment */ const { k1: kA, k2: kB, k3: kC, } = {...old_obj} console.log(`kA = ${kA},`, `kB = ${kB},`, `kC = ${kC}\n`); // kA = 111, kB = 222, kC = 333 const new_obj = Object.assign( {}, { kA, kB, kC } ); console.log(`new_obj =\n`, new_obj); // {kA: "111", kB: "222", kC: "333"}
重命名对象键的另一种方法:
让我们考虑这个对象:
let obj = {"name": "John", "id": 1, "last_name": "Doe"}
让我们重命名name key为first_name:
let { name: first_name, ...rest } = obj;
obj = { first_name, ...rest }
现在对象是:
{"first_name": "John", "id": 1, "last_name": "Doe"}
如果有人需要重命名object的键:
const renameKeyObject = (obj, oldKey, newKey) => { 如果 (旧键 === 新键) 返回 volj; Object.keys(obj).forEach((key) => { if (key === oldKey) { obj[newKey] = obj[key]; 删除 obj[键]; } else if (obj[key] !== null &&; typeof obj[key] === “object”) { obj[key] = renameKeyObject(obj[key], oldKey, newKey); } }); 返回卷; };
简单地这么做会有什么问题吗?
someObject = {...someObject, [newKey]: someObject.oldKey}
delete someObject.oldKey
如果愿意,可以将其包装在函数中:
const renameObjectKey = (object, oldKey, newKey) => {
// if keys are the same, do nothing
if (oldKey === newKey) return;
// if old key doesn't exist, do nothing (alternatively, throw an error)
if (!object.oldKey) return;
// if new key already exists on object, do nothing (again - alternatively, throw an error)
if (object.newKey !== undefined) return;
object = { ...object, [newKey]: object[oldKey] };
delete object[oldKey];
return { ...object };
};
// in use
let myObject = {
keyOne: 'abc',
keyTwo: 123
};
// avoids mutating original
let renamed = renameObjectKey(myObject, 'keyTwo', 'renamedKey');
console.log(myObject, renamed);
// myObject
/* {
"keyOne": "abc",
"keyTwo": 123,
} */
// renamed
/* {
"keyOne": "abc",
"renamedKey": 123,
} */
我想这么做
const originalObj = {
a: 1,
b: 2,
c: 3, // need replace this 'c' key into 'd'
};
const { c, ...rest } = originalObj;
const newObj = { ...rest, d: c };
console.log({ originalObj, newObj });