JavaScript: Object Rename Key

Jean Vincent picture Jean Vincent · Jan 10, 2011 · Viewed 325.6k times · Source

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[ old_key ];

Answer

Valeriu Paloş picture Valeriu Paloş · Jan 29, 2013

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.