Rename Object Key in JavaScript
Last Updated :
13 Dec, 2023
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:
Method 1: 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
let capitals = [{
"Burma" : "Naypyitaw"
}];
console.log(capitals);
function rename() {
capitals = capitals.map( function (obj) {
obj[ 'Myanmar' ] = obj[ 'Burma' ];
delete obj[ 'Burma' ];
return obj;
});
console.log(capitals);
}
rename();
|
Output
[ { Burma: 'Naypyitaw' } ]
[ { Myanmar: 'Naypyitaw' } ]
Method 2: Using defineProperty()
In this approach, we will rename the given object key by utilizing defineProperty() to manipulate the property of the object.
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 that to be modified, the name of the key, and the description attribute respectively in that order.
Syntax:
Object.defineProperty(obj, key, description) ;
Example: In this example, we have used defineProperty() to rename Object key.
Javascript
let capitals = [{
"Persia" : "Tehran"
}];
console.log(capitals);
function renameKey(obj, old_key, new_key) {
if (old_key !== new_key) {
Object.defineProperty(obj, new_key,
Object.getOwnPropertyDescriptor(obj, old_key));
delete obj[old_key];
}
}
function rename() {
capitals.forEach(obj => renameKey(obj, 'Persia' , 'Iran' ));
console.log(capitals);
}
rename();
|
Output
[ { Persia: 'Tehran' } ]
[ { Iran: 'Tehran' } ]
This method allows you to copy the properties of one or more source objects to a target object.
Syntax:
Object.assign(target, ...sources);
Example: In this example, we have used Object.assign() method.
Javascript
let myObject = { oldKey: "value" };
let renamedObject = Object.assign({}, { newKey: myObject.oldKey });
console.log(renamedObject);
|
Output
{ newKey: 'value' }
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...