EN
JavaScript - rename object key
0
points
In this article, we would like to show you how to rename object key in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
var myObject = { id: 1, color: 'red' };
var oldKey = 'color';
var newKey = 'background';
if (oldKey !== newKey) {
myObject[newKey] = myObject[oldKey];
delete myObject[oldKey];
}
console.log(JSON.stringify(myObject)); // {"id":1,"background":"red"}
1. Alternative solution
In this example, we use defineProperty()
method to define a new property and delete the old one.
The getOwnPropertyDescriptor()
to guarantees that the renamed property will behave identically to the original one.
// ONLINE-RUNNER:browser;
var myObject = { id: 1, color: 'red' };
var oldKey = 'color';
var newKey = 'background';
if (oldKey !== newKey) {
var value = Object.getOwnPropertyDescriptor(myObject, oldKey);
Object.defineProperty(myObject, newKey, value); // equivalent to: this[newKey] = value;
Object.defineProperty(myObject, oldKey, {set: undefined}); // equivalent to: delete this[oldKey];
}
console.log(JSON.stringify(myObject)); // {"id":1,"background":"red"}
2. Reusable code
In this example, we extend Object
by using Object.prototype
, adding custom renameKey()
function. After that, we can use it on every object instance.
// ONLINE-RUNNER:browser;
Object.prototype.renameKey = function(oldKey, newKey) {
if (oldKey !== newKey) {
var value = Object.getOwnPropertyDescriptor(this, oldKey);
Object.defineProperty(this, newKey, value); // equivalent to: this[newKey] = value;
Object.defineProperty(this, oldKey, {set: undefined}); // equivalent to: delete this[oldKey];
}
};
// Usage example:
var myObject = {id: 1, color: 'red'};
myObject.renameKey('color', 'background');
console.log(JSON.stringify(myObject)); // {"id":1,"background":"red"}
Warning: by extending
Object
we should be aware how prototyping works - it can lead to bugs in the exisintg/unchanged source code.