1

I am making an API call in React and I would like to add an additional price property to the results, with each property having a different value for each result.

For example...

API response:

 {
     id: 456
     name: "capuccino",
     type: "coffee",
  },
  {
     id: 457
     name: "latte",
     type: "coffee",
  },
  {
     id: 458
     name: "americano",
     type: "coffee",
   }

Is there a way to dynamically add an additional price property, each with a different value to get the result below?

  {
     id: 456
     name: "capuccino",
     type: "coffee",
     **price: 5.99**   
  },
  {
     id: 457
     name: "latte",
     type: "coffee",
     **price: 10.00**
  },
  {
     id: 458
     name: "americano",
     type: "coffee",
     **price: 8.90**
   }
itsverde
  • 105
  • 1
  • 9
  • You can just iterate over the array and add the property to the element. Like `data.forEach((item, i) => { item.price = prices[i]; })` (note that React is completely irrelevant here) –  May 02 '22 at 12:50
  • it's an array of objects – itsverde May 02 '22 at 12:53
  • I did come across this post however all the property values were the same in this case so that's why I was stuck...answer below is helpful, now I understand. – itsverde May 02 '22 at 13:09
  • 1
    The top two answers both show how to add an `Active` property to an array. How is that not the exact same thing? You didn't even post an attempt of doing this. Are you talking about the index thing? As in, merging two arrays? There's also existing answers for that. –  May 02 '22 at 13:16

1 Answers1

0

You could create a prices array and use map() and the index to map the price to the correct object.

const response = [{
    id: 456,
    name: "capuccino",
    type: "coffee",
  },
  {
    id: 457,
    name: "latte",
    type: "coffee",
  },
  {
    id: 458,
    name: "americano",
    type: "coffee",
  }
];

const prices = [2, 5, 27];

const result = response.map((o, i) => ({ ...o, price: prices[i] }));

console.log(result);
axtcknj
  • 367
  • 1
  • 9