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

一种非优化的方式是:

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

当前回答

我想这么做

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 });

其他回答

我会这样做:

function renameKeys(dict, keyMap) {
  return _.reduce(dict, function(newDict, val, oldKey) {
    var newKey = keyMap[oldKey] || oldKey
    newDict[newKey] = val 
    return newDict
  }, {})
}

重命名对象键的另一种方法:

让我们考虑这个对象:

let obj = {"name": "John", "id": 1, "last_name": "Doe"}

让我们重命名name key为first_name:

let { name: first_name, ...rest } = obj;
obj = { first_name, ...rest }

现在对象是:

{"first_name": "John", "id": 1, "last_name": "Doe"}

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

我只想用ES6(ES2015)的方式!

我们需要跟上时代!

const old_obj = { k1: `111`, k2: `222`, k3: `333` }; console.log(`old_obj =\n`, old_obj); // {k1: "111", k2: "222", k3: "333"} /** * @author xgqfrms * @description ES6 ...spread & Destructuring Assignment */ const { k1: kA, k2: kB, k3: kC, } = {...old_obj} console.log(`kA = ${kA},`, `kB = ${kB},`, `kC = ${kC}\n`); // kA = 111, kB = 222, kC = 333 const new_obj = Object.assign( {}, { kA, kB, kC } ); console.log(`new_obj =\n`, new_obj); // {kA: "111", kB: "222", kC: "333"}

就我个人而言,重命名对象中的键而不实现额外的沉重插件和轮子的最有效的方法:

var str = JSON.stringify(object);
str = str.replace(/oldKey/g, 'newKey');
str = str.replace(/oldKey2/g, 'newKey2');

object = JSON.parse(str);

如果对象具有无效的结构,还可以将其封装在try-catch中。工作完美无缺:)