简体   繁体   中英

How to return an array of objects from array of arrays with array.map method?

I use React and I have this array in Redux Persist reducer:

const data = [["2020-09-14","15:00","60","Info","April Tucker","Other","yes"],
["2020-09-14","2:00","50","Text","April Tucker","Other","yes"]]

I want to return a new array of objects (for each array in the array) with some of the values from the data array. Example of how it should look like:

let events = [{ title: data[0][3], date: data[0][0] },{ title: data[1][3], date: data[1][0]}] 

I tried to use array.map method:

 let events [
    data.map((index) => ({
      title: data[index][3],
      date: data[index][0],
    })),
  ]

This does not work as I expected. How to do it properly?

The .map function gives you each item of the array as a parameter in the callback function.

Use it like so:

 const data = [ ["2020-09-14", "15:00", "60", "Info", "April Tucker", "Other", "yes"], ["2020-09-14", "2:00", "50", "Text", "April Tucker", "Other", "yes"] ] let events = data.map(item => ({ title: item[3], date: item[0], })) console.log(events)

the callback on the map function takes the actual array item as the first argument and the index as the second, while your function takes index as the first.

Also, you are putting the result of the map operation inside square brackets [ ] . The array produced by map will be placed as the first element in a new array, while you probably don't want that

let events = data.map(arr => ({
  title: arr[3],
  date: arr[0],
})

With destructuring and shorthand property names it's easy as one two three

 const data = [["2020-09-14","15:00","60","Info","April Tucker","Other","yes"], ["2020-09-14","2:00","50","Text","April Tucker","Other","yes"]] let events = data.map(([date,,,title]) => ({title, date}) ) console.log(events)

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