Assignment of variable

Renaming the object by simple assignment of variables. After the assignment of variables or variables, we will delete the old key, and value pair and print the new key-value pair.

Syntax:

obj['New key'] = obj['old key'];

Note: Renaming the object by simple assignment of variable could be applied on multiple keys and value pairs. 

Example: In this example, we have used the assignment of the variable method.

Javascript
// JavaScript Program to illustrate renaming

// Creating an object 'capital' with
// key "Burma" and value "Naypitaw"
let capitals = [{ 
    "Burma": "Naypyitaw"
}];

console.log(capitals);

// Function to rename on button click
function rename() { 
    capitals = capitals.map(function (obj) {

        // Assign new key
        obj['Myanmar'] = obj['Burma']; 

        // Delete old key
        delete obj['Burma']; 

        return obj;
    });
    console.log(capitals);
}

rename();

Output
[ { Burma: 'Naypyitaw' } ]
[ { Myanmar: 'Naypyitaw' } ]

Rename Object Key in JavaScript

In JavaScript, objects are used to store the collection of various data. It is a collection of properties. A property is a “key: value” pair where Keys are known as ‘property name’ and are used to identify values. Since JavaScript doesn’t provide an inbuilt function to rename an object key. So we will look at different approaches to accomplish this.

Below are the different approaches to rename Object key in JavaScript:

Table of Content

  • Assignment of variable
  • Using defineProperty()
  • Using Object.assign()
  • Object Destructuring with spread operator
  • Using a temporary variable and delete

Similar Reads

Assignment of variable

Renaming the object by simple assignment of variables. After the assignment of variables or variables, we will delete the old key, and value pair and print the new key-value pair....

Using defineProperty()

In this approach, we will rename the given object key by utilizing defineProperty() to manipulate the property of the object....

Using Object.assign()

This method allows you to copy the properties of one or more source objects to a target object....

Object Destructuring with spread operator

Object destructuring and spread operator involve extracting properties from an object, creating a new object with a renamed key using spread syntax, and including the remaining properties. This method is concise and efficient for key renaming in JavaScript....

Using a temporary variable and delete

This method involves creating a temporary variable to store the value associated with the old key, assigning the value to the new key, and then deleting the old key from the object....

Contact Us