How to Rename an Object's Key in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Rename an Object's Key in JavaScript #

To rename a key in an object:

  1. Use bracket notation to assign the value of the old key to the new key.
  2. Use the delete operator to delete the old key.
  3. 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 to 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 result and is a bit cleaner. However, some of the limitations that exist when accessing object properties with dot notation, don't apply to bracket [] notation access.

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 to 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 to use the first approach. The second approach achieves the same goal, however it is a bit more indirect and harder to read.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.