How to Rename an Object's Key in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 30 20212 min read

banner

Photo by Farrel Nobel

Rename an Object's Key in JavaScript #

To rename the key of an object, use bracket notation to assign the value of the old key to the new key, e.g. obj['newKey'] = obj['oldKey']. Then use the delete operator to delete the old key - delete obj['oldKey']. The object will contain only the key with the new name.

index.js
const obj = {oldKey: 'value'}; obj['newKey'] = obj['oldKey']; delete obj['oldKey']; console.log(obj); // ๐Ÿ‘‰๏ธ {newKey: 'value'}

We used bracket [] notation to assign the value of oldKey to the newKey property in the object.

The last step is use the delete operator to delete the old key from the object.

This practically renames the key in the object.

If the names of the keys in the object don't contain spaces or start with special characters, you can also use dot notation.
index.js
const obj = {oldKey: 'value'}; obj.newKey = obj.oldKey; delete obj.oldKey; console.log(obj); // ๐Ÿ‘‰๏ธ {newKey: 'value'}

This code snippet achieves the same goal and is a bit cleaner. However, some of the limitations that exist when accessing object properties with dot notation, don't exist when using bracket [] notation.

An alternative, but also very common approach is to use the Object.assign method.

index.js
const obj = {oldKey: 'value'}; delete Object.assign(obj, {newKey: obj.oldKey})['oldKey']; console.log(obj); // ๐Ÿ‘‰๏ธ {newKey: 'value'}

The Object.assign method takes 2 parameters:

  1. the target object - the object to which the sources' properties are applied
  2. the sources - the source objects that contain the properties to be applied to the target object.

The method returns the target object with the provided properties applied.

We added the newKey property on the object and set it to the value of the oldKey property.

The last step is to use the delete operator to delete the oldKey property.

My personal preference is the first approach. The second approach achieves the same goal, however it is a bit more indirect and harder to read.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee