user image

Shilpa
Published in : 2022-03-05

Rename key inside Object {}

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!

Comments

Rakshit Date : 2022-03-05

Best answers

34

Best answers

34

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.

Shilpa Date : 2022-03-05

Best answers

10

Best answers

10

delete Object.assign(obj, {[username]: obj[email] })[email];

This approach works, and it is optimized way to achieve my questions.

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

Import Swiper into Angular causes error
Publish date: 2022-03-05 | Comments: 1

Tag: Angular

How to translate Angular application easily?
Publish date: 2022-03-03 | Comments: 2

Tag: Angular

Angular: HTML anchor tag with #idref issue
Publish date: 2022-03-01 | Comments: 2

Tag: Angular

Static code analysis tools integration with latest Angular version
Publish date: 2022-02-25 | Comments: 1

Tag: Angular

How to reload Angular component without refreshing page?
Publish date: 2022-03-02 | Comments: 1

Tag: Angular

How to call event handler onload for Angular application?
Publish date: 2022-03-02 | Comments: 2

Tag: Angular