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

一种非优化的方式是:

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

当前回答

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

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
}

其他回答

在寻找了很多答案后,这是我最好的解决方案:

const renameKey = (oldKey, newKey) => {
  _.reduce(obj, (newObj, value, key) => {
    newObj[oldKey === key ? newKey : key] = value
    return newObj
  }, {})
}

很明显,它没有替换原来的键,而是构造了一个新对象。 问题中的方法有效,但会改变对象的顺序,因为它将新的键-值添加到最后一个对象上。

还有一种最强大的REDUCE方法。

数据= {\ key1:“value1”,key2:“value2”,key3:“value3”}; 键文件夹= {\ key1:“firstkey”,key2:“secondkey”,key3:“thirdkey” mappedData = Object.keys . .还原((obj,k) =>对象。assign(obj, {\ [keyMap]]:数据[k]},{\}; 控制台日志(mappedData); 第一个“value1”、“secondkey”、“value2”、“thirdkey”、“value3”……

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

为每个键添加前缀:

const obj = {foo: 'bar'}

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

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

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

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}