user image

Shilpa
Published in : 2022-03-05

Is it possible to update Object key without generating new object and delete older object?

Javascript

I am frustrated by using the below approach in javascript. what could be the possible solution to not create a new object and delete the key?

var rowObj = { name : 'shilpa', id: 1};rowObj.name_new= rowObj.name;rowObj.id_new = rowObj.id;delete rowObj.name;delete rowObj.id;alert(JSON.stringify(rowObj))

An optimized approach for this issue will be highly appreciated.

Comments

Rakshit Date : 2022-03-05

Best answers

34

Best answers

34

Definitely, you are not creating another object from ‘rowObj’ using your code.

Inside object, if you want to add suffix or prefix to all the keys as ‘_new’ or ‘new_’, you need to loop your all the keys.

To do so, use “Object.keys(rowObj)” method, it will give you an array of all available keys inside rowObj.

Try below code,

var key;for (key in rowObj) { if (rowObj.hasOwnProperty(key)) { rowObj[key + "_new"] = rowObj[key]; delete rowObj[key]; // Or You can put rowObj[key] = undefined, if is ok to use for your code. }}

Hope, it will work for you!

Shilpa Date : 2022-03-05

Best answers

10

Best answers

10

Yeah, this can be done in the best way, thanks for sharing.

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

How to move a div with its content to TinyMEC editor?
Publish date: 2022-02-11 | Comments: 0

Tag: Javascript

How to open URL in new tab & focus on it in Javascript?
Publish date: 2021-12-22 | Comments: 1

Tag: Javascript

Vanilla JavaScript Next & prev Navigation
Publish date: 2022-02-22 | Comments: 1

Tag: Javascript

Can I read a local json, image or text file from Javascript?
Publish date: 2022-03-03 | Comments: 1

Tag: Javascript

JavaScript variable for Changing CSS Height
Publish date: 2022-02-12 | Comments: 1

Tag: Javascript

How can I switch between two background-colors using js setinterval( )
Publish date: 2022-02-22 | Comments: 1

Tag: Javascript

javascript: Uncaught TypeError: undefined is not a function
Publish date: 2022-03-02 | Comments: 2

Tag: Javascript