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 ];
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.
Syntax: obj['New key'] = obj['old key']; Note: Renaming the object by simple assignment of variable could be applied on multiple key, value pairs.
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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With