How to use a temporary variable and delete In Javascript

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.

Example:

JavaScript
// Sample object
let obj = {
    oldKey: "value"
};

// Store the value associated with the old key in a temporary variable
let temp = obj.oldKey;

// Assign the value to the new key
obj.newKey = temp;

// Delete the old key
delete obj.oldKey;

// Print the updated object
console.log(obj); // Output: { newKey: "value" }

Output
{ newKey: 'value' }




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