[英]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:我使用 React 并且在 Redux Persist 减速器中有这个数组:
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:我尝试使用 array.map 方法:
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. .map
函数为您提供数组的每一项作为回调函数中的参数。
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. map
函数上的回调将实际数组项作为第一个参数,将索引作为第二个参数,而您的函数将index
作为第一个参数。
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 map 生成的数组将作为新数组中的第一个元素放置,而您可能不希望那样
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.