是否有一个聪明的(即优化)方法重命名一个关键在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原型。也许可以使用流畅的界面样式使多个重命名流动。
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 Specific
我希望语法不是这么复杂,但它肯定是很好的有更多的控制。
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 iterate(instance) {
for (let child of instance.tree_down) iterate(child);
instance.children = instance.tree_down;
delete instance.tree_down;
}
iterate(link_hierarchy);
console.log(link_hierarchy);
我想这么做
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 });
const clone = (obj) => Object.assign({}, obj);
const renameKey = (object, key, newKey) => {
const clonedObj = clone(object);
const targetKey = clonedObj[key];
delete clonedObj[key];
clonedObj[newKey] = targetKey;
return clonedObj;
};
let contact = {radiant: 11, dire: 22};
contact = renameKey(contact, 'radiant', 'aplha');
contact = renameKey(contact, 'dire', 'omega');
console.log(contact); // { aplha: 11, omega: 22 };
我想说,从概念的角度来看,保持旧对象(来自web服务的对象)原样,并将所需的值放在新对象中会更好。我假设您在某个地方提取特定的字段,如果不是在客户机上,那么至少是在服务器上。事实上,您选择使用与web服务相同的字段名,只是小写,这并没有真正改变这一点。所以,我建议你这样做:
var myObj = {
field1: theirObj.FIELD1,
field2: theirObj.FIELD2,
(etc)
}
当然,我在这里做了各种各样的假设,这可能是不正确的。如果这对你不适用,或者它太慢了(是吗?我还没有测试过,但我想随着字段数量的增加,差异会越来越小),请忽略所有这些:)
如果你不想这样做,并且你只需要支持特定的浏览器,你也可以使用新的getter来返回“大写(字段)”。:更多信息请参见http://robertnyman.com/2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/和该页面上的链接。
编辑:
令人难以置信的是,这也几乎是两倍的速度,至少在我的FF3.5工作。参见:http://jsperf.com/spiny001