是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
当前回答
如果有人需要重命名属性列表:
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"}
其他回答
如果你想保持对象的相同顺序
changeObjectKeyName(objectToChange, oldKeyName: string, newKeyName: string){
const otherKeys = cloneDeep(objectToChange);
delete otherKeys[oldKeyName];
const changedKey = objectToChange[oldKeyName];
return {...{[newKeyName] : changedKey} , ...otherKeys};
}
使用方法:
changeObjectKeyName ( {'a' : 1}, 'a', 'A');
您可以将工作包装在一个函数中,并将其分配给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;
}
}
);
我的方法,改编好的@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});
为每个键添加前缀:
const obj = {foo: 'bar'}
const altObj = Object.fromEntries(
Object.entries(obj).map(([key, value]) =>
// Modify key here
[`x-${key}`, value]
)
)
// altObj = {'x-foo': 'bar'}
在您最喜欢的编辑器中尝试一下
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
}