Shilpa
5 Mar 2022
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.
Rakshit
5 Mar 2022
Best Answer
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!
© 2024 Copyrights reserved for web-brackets.com