是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?

一种非优化的方式是:

o[ new_key ] = o[ old_key ];
delete o[ old_key ];

当前回答

使用对象解构和展开运算符的变体:

const old_obj = {
    k1: `111`,
    k2: `222`,
    k3: `333`
};    

// destructuring, with renaming. The variable 'rest' will hold those values not assigned to kA, kB, or kC.
const {
    k1: kA, 
    k2: kB, 
    k3: kC,
    ...rest
} = old_obj;
    

// now create a new object, with the renamed properties kA, kB, kC; 
// spread the remaining original properties in the 'rest' variable
const newObj = {kA, kB, kC, ...rest};

对于一个键,这可以很简单:

const { k1: kA, ...rest } = old_obj;
const new_obj = { kA, ...rest }

你也可能喜欢更“传统”的风格:

const { k1, ...rest } = old_obj
const new_obj = { kA: k1, ...rest}

其他回答

如果你要改变源对象,ES6可以在一行中完成。

delete Object.assign(o, {[newKey]: o[oldKey] })[oldKey];

如果你想创建一个新对象,可以用两行。

const newObject = {};
delete Object.assign(newObject, o, {[newKey]: o[oldKey] })[oldKey];

一般来说,如果你想获得一个新的对象(不改变原来的对象),根据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}

如果有人需要重命名属性列表:

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"}

如果有人需要重命名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); } }); 返回卷; };

在您最喜欢的编辑器中尝试一下

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
}