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:

 

1. Alternative solution

Edit

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.

2. Reusable code

Edit

In this example, we extend Object by using Object.prototype, adding custom renameKey() function. After that, we can use it on every object instance.

Warning: by extending Object we should be aware how prototyping works - it can lead to bugs in the exisintg/unchanged source code.

References

Edit
  1. Object.defineProperty() - JavaScript | MDN
  2. Object.getOwnPropertyDescriptor() - JavaScript | MDN
1
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