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:
// 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