I need to replace array of object in javascript. Here is my data variable and I want to update data variable
const data = [{name: "poran", id: "22"}];
Expected value:
data = [{value: "poran", age: "22"}];
How can I replace array of object?
I need to replace array of object in javascript. Here is my data variable and I want to update data variable
const data = [{name: "poran", id: "22"}];
Expected value:
data = [{value: "poran", age: "22"}];
How can I replace array of object?
You can create a new array with the use of .map() and some Object Destructuring:
const data = [{name:"poran",id:"22"}];
const result = data.map(({ name:value , id:age }) => ({value, age}));
console.log(result);
{ name:value , id:age } - very nice +1 :)You can use a .forEach() loop over the array:
data.forEach((obj) {
obj.value = obj.name;
obj.age = obj.id;
delete obj.name;
delete obj.id;
});
It's a little simpler if you just make a new array with .map(), but if you need to keep the old objects because there are lots of other properties, this would probably be a little less messy.