Shilpa
5 Mar 2022
Angular
I want to rename the key from the object.
Previously I was using ‘email’ key everywhere in all JSON responses, I want to change the email key to ‘username’.
obj[ username ] = obj[ email];
delete obj[ email];
Can you please tell me what is the optimized way to do it? I feel low confident while deleting object key in above way!
Rakshit
5 Mar 2022
Best Answer
Yes, you can change it, try below code.
if (email !== username ) {
Object.defineProperty(obj, username ,
Object.getOwnPropertyDescriptor(obj, email));
delete obj[email];
}
Using ‘defineProperty’, you can update your key name easily.
If you are using > ES6 then you can achieve it with single line approach.
delete Object.assign(obj, {[username]: obj[email] })[email];
Try any of above two solution, it will rename your key name for sure.
© 2024 Copyrights reserved for web-brackets.com