Rename object key in JavaScript
JavaScript doesn’t provide an inbuilt function to rename an object key. So we will look at different approaches to accomplish this in this article.
Keys:
In JavaScript, objects are used to store collection of various data. It is a collection of properties. A property is a “key:value” pair. Keys are known as ‘property name’ and are used to identify values.
Method 1: Renaming the object by simple assignment of variables. After the assignment of variable or variables we will delete the old key,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 key, value pairs.
Example:
<!DOCTYPE html> <html> <head> <title> JavaScript: Object Rename Key </title> </head> <body> <center> <h1 style= "color:green" >GeeksforGeeks</h1> <button type= "button" onclick= "rename()" > rename </button> <script> // JavaScript Program to // illustrate renaming var capitals = [{ // creating an object 'capital' with "Burma" : "Naypyitaw" // key "Burma" and value "Naypitaw" }]; console.log(capitals); function rename() { // function to rename on button click capitals = capitals.map( function (obj) { obj[ 'Myanmar' ] = obj[ 'Burma' ]; // Assign new key delete obj[ 'Burma' ]; // Delete old key return obj; }); console.log(capitals); } </script> </body> </html> |
Output before rename:
Output after rename:
Method 2:
In this approach we will rename the given object key by utilizing defineProperty() to manipulate the property of the object.
defineProperty():
This static method is used to define a new property of an object or modify an existing one, and returns the object. It accepts 3 parameters. They are: Object to be modified, name of the key, and the description attribute respectively in that order.
Syntax:
Object.defineProperty(obj, key, description)
Example:
<!DOCTYPE html> <html> <head> <title> JavaScript: Object Rename Key </title> </head> <body> <center> <h1 style= "color:green" >GeeksforGeeks</h1> <button type = "button" onclick = "rename()" > rename </button> <script> // JavaScript Program to // illustrate renaming key var capitals= [{ // creating an object 'capital' with "Persia" : "Tehran" // key "Persia" and value "Tehran" }]; console.log(capitals); // function to rename old key function renameKey(obj, old_key, new_key) { // check if old key = new key if (old_key !== new_key) { Object.defineProperty(obj, new_key, // modify old key // fetch description from object Object.getOwnPropertyDescriptor(obj, old_key)); delete obj[old_key]; // delete old key } } function rename(){ capitals.forEach(obj => renameKey(obj, 'Persia' , 'Iran' )); console.log(capitals); } </script> </body> </html> |
Output before renaming:
Output after renaming: