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 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
Contact Us