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

一种非优化的方式是:

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

当前回答

我会这样做:

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

其他回答

我会这样做:

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

重命名键,但避免改变原始对象参数

oldJson=[{firstName:'s1',lastName:'v1'},
         {firstName:'s2',lastName:'v2'},
         {firstName:'s3',lastName:'v3'}]

newJson = oldJson.map(rec => {
  return {
    'Last Name': rec.lastName,
    'First Name': rec.firstName,  
     }
  })
output: [{Last Name:"v1",First Name:"s1"},
         {Last Name:"v2",First Name:"s2"},
         {Last Name:"v3",First Name:"s3"}]

最好有一个新的数组

为每个键添加前缀:

const obj = {foo: 'bar'}

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

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

还有一种最强大的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”……

我认为最完整(和正确)的方法是:

if (old_key !== new_key) {
    Object.defineProperty(o, new_key,
        Object.getOwnPropertyDescriptor(o, old_key));
    delete o[old_key];
}

此方法确保重命名的属性的行为与原始属性相同。

另外,在我看来,把它包装成一个函数/方法,并把它放入对象的可能性。原型与你的问题无关。