Darren
Darren

Reputation: 2290

Defining the data in an array

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.

Upvotes: 1

Views: 50

Answers (4)

Paul Fitzgerald
Paul Fitzgerald

Reputation: 12129

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);
})

Upvotes: 1

Shahriat Hossain
Shahriat Hossain

Reputation: 340

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

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

Upvotes: 0

DSCH
DSCH

Reputation: 2366

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

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074168

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).

Upvotes: 0

Related Questions