如何在React上修改数组

时间:2019-05-05 14:13:29

标签: arrays reactjs axios

在api这样的返回值中,

[
    "Action",
    "Comedy",
    "Documentary",
    "Drama"
]

我需要像这样修改上面的数组,

 const techCompanies = [
      { label: "Action", value: 1 },
      { label: "Comedy", value: 2 },
      { label: "Documentary", value: 3 },
      { label: "Drama", value: 4 }
   ];

我用Axios来获取数据,

const response = await axios.get("http://localhost:3000/Movie/v1.0/genre");

1 个答案:

答案 0 :(得分:3)

这是一个数组,因此您可以使用 .map() 函数执行此操作:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

const arr = ["Action", "Comedy", "Documentary", "Drama"];

arr.map((arrElement, index) => ({ label: arrElement, value: index }));