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

一种非优化的方式是:

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

当前回答

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

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

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

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

其他回答

我想说,从概念的角度来看,保持旧对象(来自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' };

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

我只想用ES6(ES2015)的方式!

我们需要跟上时代!

const old_obj = { k1: `111`, k2: `222`, k3: `333` }; console.log(`old_obj =\n`, old_obj); // {k1: "111", k2: "222", k3: "333"} /** * @author xgqfrms * @description ES6 ...spread & Destructuring Assignment */ const { k1: kA, k2: kB, k3: kC, } = {...old_obj} console.log(`kA = ${kA},`, `kB = ${kB},`, `kC = ${kC}\n`); // kA = 111, kB = 222, kC = 333 const new_obj = Object.assign( {}, { kA, kB, kC } ); console.log(`new_obj =\n`, new_obj); // {kA: "111", kB: "222", kC: "333"}

您可以将工作包装在一个函数中,并将其分配给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;
        }
    }
);