2016-04-24 88 views
2

我正在制作反馈应用程序,受Michael's tutorial(也有a video)的启发,我尝试使用Lodash's _.map函数尝试在数组内部传递数组时遇到一些问题。这是信息我映射:使用ES6在React中映射对象中的数组

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' 
         } 
        ] 

       } 


      ]; 

我传递到这样的组分(本作品):

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

这工作完全正常,将每个“事件”对象(here's a screenshot of it working)

然后我试图解构和映射“的艺术家:”每个事件的对象是这样的:

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

这是我得到的结果,这是接近,但不是我所需要的:enter image description here

我需要这些进一步分离得到:

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

等等...

我看到这里有一个模式,我只是不知道如何进一步实现它。当我尝试重复相同的结构时,它会中断,然后_.map的东西。任何人都可以请给我一个这样的手,对不起长篇大论。

+1

[有没有这样的事情作为一个 “JSON阵列”(http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) – adeneo

+1

什么关于使用'_.get'?我认为它会服务于目的,你是否也可以将它提升到jsbin或者我们可以测试的一个好地方? – ArchNoob

回答

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

您的第一条评论(您删除的那条评论)解决了我的问题VyvIT,非常感谢!我不能相信我花了这么多时间,但我没有注意到它:D –

+0

没问题,这里有一个解决方案,将flatMap中的艺术家从初始事件数组中抽象出来。 – VyvIT

0

哦,我发现由于VyvIT的评论的问题(他删掉了他的评论),它在这里:

const { event, venue, venuePicture, when, genres, artists } = this.props.events; 
    _.map({artists}, (artist, index) => <ItemArtist key={index} {...artist} {...props}/>); 

‘艺术家’不应该被解构(大括号),应该是这样的:

_.map(artists, (artist, index) => <ItemArtist key={index} {...artist} {...props}/>); 

非常感谢你们!

相关问题