是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
当前回答
如果有人需要重命名object的键:
const renameKeyObject = (obj, oldKey, newKey) => { 如果 (旧键 === 新键) 返回 volj; Object.keys(obj).forEach((key) => { if (key === oldKey) { obj[newKey] = obj[key]; 删除 obj[键]; } else if (obj[key] !== null &&; typeof obj[key] === “object”) { obj[key] = renameKeyObject(obj[key], oldKey, newKey); } }); 返回卷; };
其他回答
我认为最完整(和正确)的方法是:
if (old_key !== new_key) {
Object.defineProperty(o, new_key,
Object.getOwnPropertyDescriptor(o, old_key));
delete o[old_key];
}
此方法确保重命名的属性的行为与原始属性相同。
另外,在我看来,把它包装成一个函数/方法,并把它放入对象的可能性。原型与你的问题无关。
尝试使用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);
我的方法,改编好的@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});
如果你不想改变你的数据,考虑这个函数…
renameProp = (oldProp, newProp, { [oldProp]: old, ...others }) => ({
[newProp]: old,
...others
})
Yazeed Bzadough的详细解释 https://medium.com/front-end-hacking/immutably-rename-object-keys-in-javascript-5f6353c7b6dd
下面是一个typescript友好的版本:
// These generics are inferred, do not pass them in.
export const renameKey = <
OldKey extends keyof T,
NewKey extends string,
T extends Record<string, unknown>
>(
oldKey: OldKey,
newKey: NewKey extends keyof T ? never : NewKey,
userObject: T
): Record<NewKey, T[OldKey]> & Omit<T, OldKey> => {
const { [oldKey]: value, ...common } = userObject
return {
...common,
...({ [newKey]: value } as Record<NewKey, T[OldKey]>)
}
}
它将防止您破坏现有的键或将其重命名为相同的东西
在您最喜欢的编辑器中尝试一下
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
}