简体   繁体   中英

How to add useState array as a useState List

我有一个来自 api 的数组,我将它存储在一个状态中,我想将该数组存储在另一个状态中作为对象列表,其中每个数组元素都是一个带有一些 Id 的值,即原始数组 = ["value1","value2"....,"value(n)"]转换为 List = [{value: "value1", id: 1}, {value: "value2", id: 2}]

What you can do in simple terms is using a map() function. Your code should be something like this:

(value, id) => ({ value, id: id + 1 })

And here's the working snippet:

 const arr = ["value1","value2","value(n)"]; const obj = arr.map((value, id) => ({value, id})); console.log(obj);

If you want the values to be one-indexed , you can change it this way:

 const arr = ["value1", "value2", "value(n)"]; const obj = arr.map((value, id) => ({ value, id: id + 1 })); console.log(obj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM