在数组中定义数据

时间:2018-07-24 08:28:09

标签: javascript reactjs

如何从映射的数据中使用存储在数组cottageGallery中的数据?

const galleryData = components.map(g => {
   return {
      cottageGallery: g.cottageGallery,
      destinationGallery: g.destinationGallery,
      activitiesGallery: g.activitiesGallery,
   }
})

我认为它只是const cottageGallery = galleryData.cottageGallery,但这返回未定义。

4 个答案:

答案 0 :(得分:1)

不完全是,galleryData将会是一个数组,而不是一个对象,因为您正在使用javascript的map方法。如果要获取数组的第一项,可以执行以下操作-[0]是数组的第一项。

const cottageGallery = galleryData[0].cottageGallery;

要记录每个cottageGallery,您可以使用forEach并执行以下操作:

galleryData.forEach(item => {
 console.log(item.cottageGallery);
})

答案 1 :(得分:0)

galleryDatamap回调返回的对象的数组。因此,您将使用galleryData[index].cottageGallery,其中index0galleryData.length - 1的范围内(或访问数组中条目的各种方式中的任何一种,例如{{ 1}}或for-of或... more here)。

答案 2 :(得分:0)

map将返回一个数组,因此您将无法简单地访问galleryData.cottageGallery。您可能想在数组上使用.reduce(),以便结果可以是您尝试创建的对象

答案 3 :(得分:0)

您还可以使用forEach访问对象数组,如下所示:

galleryData.forEach(a => {
 console.log(a.cottageGallery);
})