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

一种非优化的方式是:

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

当前回答

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

其他回答

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

尝试使用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);

简单地这么做会有什么问题吗?

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,
} */

我想这么做

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

为每个键添加前缀:

const obj = {foo: 'bar'}

const altObj = Object.fromEntries(
  Object.entries(obj).map(([key, value]) => 
    // Modify key here
    [`x-${key}`, value]
  )
)

// altObj = {'x-foo': 'bar'}