-1

I have a json array

[{id:1,data:"test1"},{id:2,data:"test2"}]

I need to add a new element to each of the objects in the array based on the value of the "data" field. That is if the value of data is "test1", the new field data should be "test one type". The expected output is as below

[{id:1,data:"test1",type: "test1 Type"},{id:2,data:"test2",type: "test2 Type"}]

I tried with .push operation but it is adding new object to the array not updating the existing object. I am new to node NodeJs. Can you please help with this.

Borislav Stefanov
  • 533
  • 3
  • 15
  • 38
  • Spread operator might help you `[...obj, { new: 'object'}]` Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax – keviveks Nov 15 '22 at 06:29
  • How to iterate over the array and use spread. Could you help with an example – shyama moneymohan Nov 15 '22 at 06:34
  • Does this answer your question? [Change properties of every item in an array?](https://stackoverflow.com/questions/35879307/change-properties-of-every-item-in-an-array) – derpirscher Nov 15 '22 at 06:36

1 Answers1

-1

u need to map add element via map function

const data = [{id:1, data:"test1"},{id:2,data:"test2"}];
data.map(element => {
    element.type = `${element.data} type`
    return element;
});

console.log(data)