是否有一种聪明的(即优化的)方法来重命名 javascript 对象中的键?
一个非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
是否有一种聪明的(即优化的)方法来重命名 javascript 对象中的键?
一个非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
我相信,最完整(和正确)的方法是:
if (old_key !== new_key) {
Object.defineProperty(o, new_key,
Object.getOwnPropertyDescriptor(o, old_key));
delete o[old_key];
}
此方法可确保重命名的属性与原始属性的行为相同。
此外,在我看来,将其包装成一个函数/方法并将其放入Object.prototype
与您的问题无关。
如果您正在修改源对象,ES6 可以在一行中完成。
delete Object.assign(o, {[newKey]: o[oldKey] })[oldKey];
如果你想创建一个新对象,或者两行。
const newObject = {};
delete Object.assign(newObject, o, {[newKey]: o[oldKey] })[oldKey];
您可以将工作包装在一个函数中并将其分配给Object
原型。也许使用流畅的界面风格来进行多次重命名。
Object.prototype.renameProperty = function (oldName, newName) {
// Do nothing if the names are the same
if (oldName === newName) {
return this;
}
// Check for the old property name to avoid a ReferenceError in strict mode.
if (this.hasOwnProperty(oldName)) {
this[newName] = this[oldName];
delete this[oldName];
}
return this;
};
ECMAScript 5 特定
我希望语法不是那么复杂,但拥有更多控制权绝对是件好事。
Object.defineProperty(
Object.prototype,
'renameProperty',
{
writable : false, // Cannot alter this property
enumerable : false, // Will not show up in a for-in loop.
configurable : false, // Cannot be deleted via the delete operator
value : function (oldName, newName) {
// Do nothing if the names are the same
if (oldName === newName) {
return this;
}
// Check for the old property name to
// avoid a ReferenceError in strict mode.
if (this.hasOwnProperty(oldName)) {
this[newName] = this[oldName];
delete this[oldName];
}
return this;
}
}
);
如果有人需要重命名属性列表:
function renameKeys(obj, newKeys) {
const keyValues = Object.keys(obj).map(key => {
const newKey = newKeys[key] || key;
return { [newKey]: obj[key] };
});
return Object.assign({}, ...keyValues);
}
用法:
const obj = { a: "1", b: "2" };
const newKeys = { a: "A", c: "C" };
const renamedObj = renameKeys(obj, newKeys);
console.log(renamedObj);
// {A:"1", b:"2"}
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"}