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

一种非优化的方式是:

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

当前回答

这里的大多数答案都无法维持JS对象键值对的顺序。例如,如果您在屏幕上有一种希望修改的对象键-值对形式,那么保持对象条目的顺序就很重要。

ES6循环JS对象并将键值对替换为具有修改过的键名的新键值对的方法如下:

let newWordsObject = {};

Object.keys(oldObject).forEach(key => {
  if (key === oldKey) {
    let newPair = { [newKey]: oldObject[oldKey] };
    newWordsObject = { ...newWordsObject, ...newPair }
  } else {
    newWordsObject = { ...newWordsObject, [key]: oldObject[key] }
  }
});

该解决方案通过在旧条目的位置上添加新条目来保留条目的顺序。

其他回答

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

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

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

function iterate(instance) {
  for (let child of instance.tree_down) iterate(child);

  instance.children = instance.tree_down;
  delete instance.tree_down;
}

iterate(link_hierarchy);

console.log(link_hierarchy);

您可以将工作包装在一个函数中,并将其分配给Object原型。也许可以使用流畅的界面样式使多个重命名流动。

Object.prototype.renameProperty = function (oldName, newName) {
     // Do nothing if the names are the same
     if (oldName === newName) {
         return this;
     }
    // Check for the old property name to avoid a ReferenceError in strict mode.
    if (this.hasOwnProperty(oldName)) {
        this[newName] = this[oldName];
        delete this[oldName];
    }
    return this;
};

ECMAScript 5 Specific

我希望语法不是这么复杂,但它肯定是很好的有更多的控制。

Object.defineProperty(
    Object.prototype, 
    'renameProperty',
    {
        writable : false, // Cannot alter this property
        enumerable : false, // Will not show up in a for-in loop.
        configurable : false, // Cannot be deleted via the delete operator
        value : function (oldName, newName) {
            // Do nothing if the names are the same
            if (oldName === newName) {
                return this;
            }
            // Check for the old property name to 
            // avoid a ReferenceError in strict mode.
            if (this.hasOwnProperty(oldName)) {
                this[newName] = this[oldName];
                delete this[oldName];
            }
            return this;
        }
    }
);

我想说,从概念的角度来看,保持旧对象(来自web服务的对象)原样,并将所需的值放在新对象中会更好。我假设您在某个地方提取特定的字段,如果不是在客户机上,那么至少是在服务器上。事实上,您选择使用与web服务相同的字段名,只是小写,这并没有真正改变这一点。所以,我建议你这样做:

var myObj = {
    field1: theirObj.FIELD1, 
    field2: theirObj.FIELD2,
    (etc)
}

当然,我在这里做了各种各样的假设,这可能是不正确的。如果这对你不适用,或者它太慢了(是吗?我还没有测试过,但我想随着字段数量的增加,差异会越来越小),请忽略所有这些:)

如果你不想这样做,并且你只需要支持特定的浏览器,你也可以使用新的getter来返回“大写(字段)”。:更多信息请参见http://robertnyman.com/2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/和该页面上的链接。

编辑:

令人难以置信的是,这也几乎是两倍的速度,至少在我的FF3.5工作。参见:http://jsperf.com/spiny001

您可以使用实用程序来处理这个问题。

npm i paix
import { paix } from 'paix';

const source_object = { FirstName: "Jhon", LastName: "Doe", Ignored: true };
const replacement = { FirstName: 'first_name', LastName: 'last_name' };
const modified_object = paix(source_object, replacement);

console.log(modified_object);
// { Ignored: true, first_name: 'Jhon', last_name: 'Doe' };