Vlady Veselinov Vlady Veselinov - 7 months ago 7
Javascript Question

Mapping an array inside an object in React with ES6

I'm making a react-feed app, inspired by Michael's tutorial (there's also a video) and I encountered some trouble trying to pass an array inside an array as props using Lodash's _.map function. This is the information I'm mapping:

const events = [
{
event: 'Gods',
venue: 'Asgard',
venuePicture: 'picture1.jpg',
when: '21:00 27/04/16',
genres: ['rock', 'funk'],
artists: [
{
artist: 'Thor',
artistPicture: 'thor.jpg'
},

{
artist: 'Loki',
artistPicture: 'loki.jpg'
}
]

},

{
event: 'Humans',
venue: 'Midgard',
venuePicture: 'picture2.jpg',
when: '21:00 27/04/16',
genres: ['jazz', 'pop'],
artists: [
{
artist: 'Human1',
artistPicture: 'human1.jpg'
},

{
artist: 'Human2',
artistPicture: 'human2.jpg'
}
]

}


];


I'm passing to the component like this (this works):

renderItems(){
const props = _.omit(this.props, 'events');

return _.map(this.props.events, (event, index) => <EventsFeedItem key={index} {...event} {...props}/>);

}

render() {
return (
<section>
{this.renderItems()}
</section>
);
}


This works perfectly fine, dividing each "event" object (here's a screenshot of it working)

Then I try to destructure and map the "artists:" object of each event like this:

renderArtists() {

const { event, venue, venuePicture, when, genres, artists } = this.props.events;

const props = _.omit(this.props, 'events');
return _.map({artists}, (artist, index) => <ItemArtist key={index} {...artist} {...props}/>);

}

render() {
return (
<ul>
{this.renderArtists()}
</ul>
);
}


This is the result I'm getting, which is close, but not what I need:enter image description here

I need to separate these further to get:

{artist: "Thor"} {artistPicture: "thor.jpg"}
{artist: "Loki"} {artistPicture: "loki.jpg"}


and so on...

I see there's a pattern here, I just don't know how to implement it further. It breaks when I try to repeat the same destructure then _.map thing. Can anyone please give me a hand with this, sorry for the long post.

Answer
return _(this.props.events).flatMap('artists').map((artist, index)=><ItemArtist key={index} {...artist} {...props}/>).value();