1

How can I use the data stored in the array cottageGallery from this mapped data?

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

I thought it would simply be const cottageGallery = galleryData.cottageGallery but this returns undefined.

Darren
  • 2,176
  • 9
  • 42
  • 98
  • What's the purpose of that `map`? To create new objects with only a subset of the properties on the objects in `components`? – T.J. Crowder Jul 24 '18 at 08:30

4 Answers4

1

Not quite, galleryData is going to be an array not an object as you are using javascript's map method. If you wanted to get the first item of the array you could do the following - [0] being the first item of the array.

const cottageGallery = galleryData[0].cottageGallery;

To log each cottageGallery you could use forEach and do the following:

galleryData.forEach(item => {
 console.log(item.cottageGallery);
})
Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54
0

galleryData is an array of the objects returned by the map callback. So you'd use galleryData[index].cottageGallery, where index is in the range 0 through galleryData.length - 1 (or any of the various ways you access entries in an array, such as for-of or forEach or...more here).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thank you. I've gone with Paul Fitzgeralds answer as it was first seen but I appreciate your help. That link is also very informative. Cheers – Darren Jul 24 '18 at 08:35
  • @Darren - Totally up to you. Not sure what you mean about "first seen," but this was *posted* first. But the important thing isn't timing, it's which answer you found most helpful. Happy coding! – T.J. Crowder Jul 24 '18 at 08:50
0

map Will return an array so you won't be able to simply access galleryData.cottageGallery. You might want to use .reduce() on your array so the outcome can be the object your were trying to create

DSCH
  • 2,146
  • 1
  • 18
  • 29
0

You can also use forEach to access object array like below:

galleryData.forEach(a => {
 console.log(a.cottageGallery);
})
Shahriat Hossain
  • 340
  • 4
  • 12