Languages
[Edit]
EN

JavaScript - rename object key

0 points
Created by:
Krzysiek
741

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.

References

  1. Object.defineProperty() - JavaScript | MDN
  2. Object.getOwnPropertyDescriptor() - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join