是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
当前回答
如果你想保留迭代顺序(插入的顺序),这里有一个建议:
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
}
其他回答
如果你想保留迭代顺序(插入的顺序),这里有一个建议:
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
}
您可以使用实用程序来处理这个问题。
npm i paix
import { paix } from 'paix';
const source_object = { FirstName: "Jhon", LastName: "Doe", Ignored: true };
const replacement = { FirstName: 'first_name', LastName: 'last_name' };
const modified_object = paix(source_object, replacement);
console.log(modified_object);
// { Ignored: true, first_name: 'Jhon', last_name: 'Doe' };
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 };
在您最喜欢的编辑器中尝试一下
const obj = {1: 'a', 2: 'b', 3: 'c'}
const OLD_KEY = 1
const NEW_KEY = 10
const { [OLD_KEY]: replaceByKey, ...rest } = obj
const new_obj = {
...rest,
[NEW_KEY]: replaceByKey
}
我的方法,改编好的@Mulhoon typescript帖子,用于更改多个键:
const renameKeys = <
TOldKey extends keyof T,
TNewkey extends string,
T extends Record<string, unknown>
>(
keys: {[ key: string]: TNewkey extends TOldKey ? never : TNewkey },
obj: T
) => Object
.keys(obj)
.reduce((acc, key) => ({
...acc,
...{ [keys[key] || key]: obj[key] }
}), {});
renameKeys({id: 'value', name: 'label'}, {id: 'toto_id', name: 'toto', age: 35});