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:
xxxxxxxxxx
1
var myObject = { id: 1, color: 'red' };
2
3
var oldKey = 'color';
4
var newKey = 'background';
5
6
if (oldKey !== newKey) {
7
myObject[newKey] = myObject[oldKey];
8
delete myObject[oldKey];
9
}
10
11
console.log(JSON.stringify(myObject)); // {"id":1,"background":"red"}
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.
xxxxxxxxxx
1
var myObject = { id: 1, color: 'red' };
2
3
var oldKey = 'color';
4
var newKey = 'background';
5
6
if (oldKey !== newKey) {
7
var value = Object.getOwnPropertyDescriptor(myObject, oldKey);
8
Object.defineProperty(myObject, newKey, value); // equivalent to: this[newKey] = value;
9
Object.defineProperty(myObject, oldKey, {set: undefined}); // equivalent to: delete this[oldKey];
10
}
11
12
console.log(JSON.stringify(myObject)); // {"id":1,"background":"red"}
In this example, we extend Object
by using Object.prototype
, adding custom renameKey()
function. After that, we can use it on every object instance.
xxxxxxxxxx
1
Object.prototype.renameKey = function(oldKey, newKey) {
2
if (oldKey !== newKey) {
3
var value = Object.getOwnPropertyDescriptor(this, oldKey);
4
Object.defineProperty(this, newKey, value); // equivalent to: this[newKey] = value;
5
Object.defineProperty(this, oldKey, {set: undefined}); // equivalent to: delete this[oldKey];
6
}
7
};
8
9
10
// Usage example:
11
12
var myObject = {id: 1, color: 'red'};
13
14
myObject.renameKey('color', 'background');
15
16
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.