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