是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
当前回答
简单地这么做会有什么问题吗?
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,
} */
其他回答
如果有人需要重命名属性列表:
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"}
如果你想保留迭代顺序(插入的顺序),这里有一个建议:
const renameObjectKey = (object, oldName, newName) => {
const updatedObject = {}
for(let key in object) {
if (key === oldName) {
newObject[newName] = object[key]
} else {
newObject[key] = object[key]
}
}
object = updatedObject
}
这里的大多数答案都无法维持JS对象键值对的顺序。例如,如果您在屏幕上有一种希望修改的对象键-值对形式,那么保持对象条目的顺序就很重要。
ES6循环JS对象并将键值对替换为具有修改过的键名的新键值对的方法如下:
let newWordsObject = {};
Object.keys(oldObject).forEach(key => {
if (key === oldKey) {
let newPair = { [newKey]: oldObject[oldKey] };
newWordsObject = { ...newWordsObject, ...newPair }
} else {
newWordsObject = { ...newWordsObject, [key]: oldObject[key] }
}
});
该解决方案通过在旧条目的位置上添加新条目来保留条目的顺序。
重命名键,但避免改变原始对象参数
oldJson=[{firstName:'s1',lastName:'v1'},
{firstName:'s2',lastName:'v2'},
{firstName:'s3',lastName:'v3'}]
newJson = oldJson.map(rec => {
return {
'Last Name': rec.lastName,
'First Name': rec.firstName,
}
})
output: [{Last Name:"v1",First Name:"s1"},
{Last Name:"v2",First Name:"s2"},
{Last Name:"v3",First Name:"s3"}]
最好有一个新的数组
在寻找了很多答案后,这是我最好的解决方案:
const renameKey = (oldKey, newKey) => {
_.reduce(obj, (newObj, value, key) => {
newObj[oldKey === key ? newKey : key] = value
return newObj
}, {})
}
很明显,它没有替换原来的键,而是构造了一个新对象。 问题中的方法有效,但会改变对象的顺序,因为它将新的键-值添加到最后一个对象上。