0

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?

1
  • first data.map((index) => ({ this is wrong , data.map((item,index) => ({}) the second arg is idx not the first one Commented Sep 2, 2020 at 12:57

3 Answers 3

3

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it is pretty simple but I was trying many other solutions so I was a little bit frustrated :)
1

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

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.