向 API 添加额外的属性导致 React

Adding additional properties to API results in React

我正在 React 中进行 API 调用,我想为结果添加额外价格 属性,每个 属性 对每个结果都有不同的值。

例如...

API 回复:

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

有没有办法动态添加额外的价格属性,每个价格都有不同的值以获得下面的结果?

  {
     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**
   }

您可以创建一个 prices 数组并使用 map() 和索引将价格映射到正确的对象。

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