是否有一个聪明的(即优化)方法重命名一个关键在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;
}, {});
其他回答
我的方法,改编好的@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 originalObj = {
a: 1,
b: 2,
c: 3, // need replace this 'c' key into 'd'
};
const { c, ...rest } = originalObj;
const newObj = { ...rest, d: c };
console.log({ originalObj, newObj });
您可以尝试lodash _mapkeys。
Var用户= { 名称:“安德鲁”, id: 25日 报道:假 }; Var重命名= _。mapKeys(用户,函数(值,键){ 返回键+ "_" + user.id; }); console.log(重命名); < script src = " https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js " > < /脚本>
一般来说,如果你想获得一个新的对象(不改变原来的对象),根据keyMap重命名键-你可以使用以下基于lodash mapKeys的实现:
const {mapKeys} = require('lodash');
const renameKeys = (obj, keyMap) => _.mapKeys(obj, (value, key) => keyMap[key] || key);
使用的例子:
renameKeys({a: 1, b: 2, c: 3}, {c: 'p', a: 'm'})
> {m: 1, b: 2, p: 3}
简单地这么做会有什么问题吗?
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,
} */