[removed] Object Rename Key

前端 未结 24 1362
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 00:18

Is there a clever (i.e. optimized) way to rename a key in a javascript object?

A non-optimized way would be:

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


        
24条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 01:15

    You could wrap the work in a function and assign it to the Object prototype. Maybe use the fluent interface style to make multiple renames flow.

    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

    I wish the syntax wasn't this complex but it is definitely nice having more control.

    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;
            }
        }
    );
    

提交回复
热议问题