JavaScript: Renaming the Key of an Object’s Property

Updated: March 14, 2023 By: Wolf 3 comments

When writing code in JavaScript, there might be cases where you need to rename the key of an object’s property, such as to make the object keys more readable or consistent with a naming convention or to replace the keys based on another object that maps the values to replace.

This concise article shows you how to rename the key of a property in a JavaScript object.

The Adding & Deleting Strategy

Forgive me because I don’t know a better and shorter name for this approach. What we will do is simply create a new property with the desired name and assign the value of the old property to the new property, and then, we will delete the old property.

This is the most important and consistent point in this article. However, we can apply it in many different ways. Let’s explore them one by one.

Using the square brackets or dot notation

An example that uses square brackets:

const obj = { firstName: 'SLing', lastName: 'Academy' };

// create a new property with the same value
obj['name'] = obj['firstName'];

// dekete the old property
delete obj['firstName'];

console.log(obj);

Output:

{ lastName: 'Academy', name: 'SLing' }

If you don’t like square brackets, you can use dot notation instead:

const obj = { firstName: 'SLing', lastName: 'Academy' };

// create a new property with the same value
obj.name = obj.firstName;

// dekete the old property
delete obj.firstName;

console.log(obj);

The result will be the same.

Using the Object.assign() method

The Object.assign() method copies the values of all enumerable own properties from one or more source objects to a target object. You can use this method to create a new object with the renamed property and then assign it back to the original object.

Example:

// Using Object.assign()
let user = {name: "Wolf the Shinobi", age: 35};

// create a new object with fullName
user = Object.assign({}, user, {fullName: user.name}); 

// delete name property
delete user.name; 

console.log(user)

Output:

{ age: 35, fullName: 'Wolf the Shinobi' }

Using the spread operator

Example:

// Using spread syntax (...)
let user = { name: 'Sling Academy', age: 5 };

// create a new object with fullName
user = { ...user, fullName: user.name };

// delete name property
delete user.name;

console.log(user)

Output:

{ age: 5, fullName: 'Sling Academy' }

Afterword

We’ve gone over some practical examples that demonstrate different implementations of the technique to change the key’s name of an object’s property. Hope you find them useful. The tutorial ends here. Good luck!

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments