Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Object Rename Key

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 ]; 
like image 624
Jean Vincent Avatar asked Jan 10 '11 14:01

Jean Vincent


People also ask

Can you rename a key in an object JavaScript?

To rename a key in an object:Use bracket notation to assign the value of the old key to the new key. Use the delete operator to delete the old key. The object will contain only the key with the new name.

How do you name an object key?

Syntax: obj['New key'] = obj['old key']; Note: Renaming the object by simple assignment of variable could be applied on multiple key, value pairs.


2 Answers

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.

like image 63
Valeriu Paloş Avatar answered Sep 21 '22 13:09

Valeriu Paloş


If you're mutating your source object, ES6 can do it in one line.

delete Object.assign(o, {[newKey]: o[oldKey] })[oldKey]; 

Or two lines if you want to create a new object.

const newObject = {}; delete Object.assign(newObject, o, {[newKey]: o[oldKey] })[oldKey]; 
like image 39
nverba Avatar answered Sep 25 '22 13:09

nverba