[removed] Object Rename Key

前端 未结 24 1407
爱一瞬间的悲伤
爱一瞬间的悲伤 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:05

    The most complete (and correct) way of doing this would be, I believe:

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

    This method ensures that the renamed property behaves identically to the original one.

    Also, it seems to me that the possibility to wrap this into a function/method and put it into Object.prototype is irrelevant regarding your question.

提交回复
热议问题