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

一种非优化的方式是:

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

当前回答

如果你想保持对象的相同顺序

changeObjectKeyName(objectToChange, oldKeyName: string, newKeyName: string){
  const otherKeys = cloneDeep(objectToChange);
  delete otherKeys[oldKeyName];

  const changedKey = objectToChange[oldKeyName];
  return  {...{[newKeyName] : changedKey} , ...otherKeys};

}

使用方法:

changeObjectKeyName ( {'a' : 1}, 'a', 'A');

其他回答

const data = res
const lista = []
let newElement: any

if (data && data.length > 0) {

  data.forEach(element => {
      newElement = element

      Object.entries(newElement).map(([key, value]) =>
        Object.assign(newElement, {
          [key.toLowerCase()]: value
        }, delete newElement[key], delete newElement['_id'])
      )
    lista.push(newElement)
  })
}
return lista

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

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
}

一般来说,如果你想获得一个新的对象(不改变原来的对象),根据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(dict, keyMap) {
  return _.reduce(dict, function(newDict, val, oldKey) {
    var newKey = keyMap[oldKey] || oldKey
    newDict[newKey] = val 
    return newDict
  }, {})
}

如果你想保留迭代顺序(插入的顺序),这里有一个建议:

const renameObjectKey = (object, oldName, newName) => {

  const updatedObject = {}

  for(let key in object) {
      if (key === oldName) {
          newObject[newName] = object[key]
      } else {
          newObject[key] = object[key]
      }
  }

  object = updatedObject
}