是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
当前回答
下面是创建具有重命名键的新对象的示例。
let x = { id: "checkout", name: "git checkout", description: "checkout repository" };
let renamed = Object.entries(x).reduce((u, [n, v]) => {
u[`__${n}`] = v;
return u;
}, {});
其他回答
本页列出的一些解决方案有一些副作用:
影响键在对象中的位置,将其添加到底部(如果这对你来说很重要) 不能在IE9+中工作(如果这对你来说很重要的话)
下面是一个解决方案,它保持键的位置在相同的地方,并在IE9+兼容,但必须创建一个新的对象,可能不是最快的解决方案:
function renameObjectKey(oldObj, oldName, newName) {
const newObj = {};
Object.keys(oldObj).forEach(key => {
const value = oldObj[key];
if (key === oldName) {
newObj[newName] = value;
} else {
newObj[key] = value;
}
});
return newObj;
}
请注意:IE9在严格模式下可能不支持forEach
您可以将工作包装在一个函数中,并将其分配给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;
}
}
);
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 };
尝试使用lodash transform。
var _ = require('lodash');
obj = {
"name": "abc",
"add": "xyz"
};
var newObject = _.transform(obj, function(result, val, key) {
if (key === "add") {
result["address"] = val
} else {
result[key] = val
}
});
console.log(obj);
console.log(newObject);
还有一种最强大的REDUCE方法。
数据= {\ key1:“value1”,key2:“value2”,key3:“value3”}; 键文件夹= {\ key1:“firstkey”,key2:“secondkey”,key3:“thirdkey” mappedData = Object.keys . .还原((obj,k) =>对象。assign(obj, {\ [keyMap]]:数据[k]},{\}; 控制台日志(mappedData); 第一个“value1”、“secondkey”、“value2”、“thirdkey”、“value3”……