0

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?

1
  • To be clear: you cannot change a property name. You can add a new property and remove properties you don't want. Commented Jul 25, 2019 at 16:02

3 Answers 3

5

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);

Sign up to request clarification or add additional context in comments.

1 Comment

I first time see that syntax: { name:value , id:age } - very nice +1 :)
2

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.

Comments

0

try this:

const data = [{name:"poran",id:"22"}] const rst = data.map(res=>({value: res.name, age: res.id})); console.log(rst)

Comments