dim_dev
dim_dev

Reputation: 339

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?

Upvotes: 0

Views: 115

Answers (3)

yunzen
yunzen

Reputation: 33439

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)

Upvotes: 0

gbalduzzi
gbalduzzi

Reputation: 10176

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],
})

Upvotes: 1

Luke Storry
Luke Storry

Reputation: 6702

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)

Upvotes: 3

Related Questions