2017-07-14 42 views
-2

实施例:https://jsfiddle.net/zidski/a0ez5sy9/1/嵌套阵列.MAP没有循环母阵列

我已经创建称为ProjectAPI JSON对象。

const ProjectAPI = { 
     projects: [ 
     { 
      name: "PROJECT NAME", 
      thumbnail: "imageURL", 
      image: [ 
      "imageURL", 
      "imageURL", 
      "imageURL" 
      ] 
     },{ 
      name: "PROJECT NAME", 
      thumbnail: "imageURL", 
      image: [ 
      "imageURL", 
      "imageURL", 
      "imageURL" 
      ] 
     }], 
    all: function() { return this.projects}, 
    get: function(id) { 
    const isProject = p => p.number === id 
    return this.projects.find(isProject) 
    } 
    } 

然后我使用.MAP得到嵌套图像:

{ 
     ProjectAPI.all().map(function(item, index) { 
      return <img className="img" key={index} src={item.image[index]} /> 
     }) 
     } 

但被好像通过父阵列循环,所以我结束了6幅图像,而不是3(在实施例的jsfiddle边框红)

我该如何定位嵌套图像?

+2

'所以我结束了6个图像,而不是3'你的意思是'3图像,而不是6'? –

+0

是3张图片而不是6张。 – user1177860

回答

2

由于图像又是一个数组,因此您需要在该图上运行地图。

写这样的:

{ 
    ProjectAPI.all().map((item, index) => { 
     return item.image.map((el,j) => <img className="img" key={j} src={el} />) 
    }) 
} 

更新:

你想第一个对象的前三个图像,所以您不需要使用嵌套的地图,就这样写:

ProjectAPI.all()[0].image.map((el,i) => <img className="img" key={i} src={el} />) 

Fiddle with all the images

Fiddle with only three images

+0

也许item.image.map? –

+0

@Jonasw对不起,我的错误,更新了答案谢谢:) –

+0

如果我只想得到前3张图片,现在它获取所有图片 – user1177860

1

问题是这样的:

src={item.image[index]} 

indexprojects阵列内的索引,它从0..n,其中nprojects阵列中的对象的数量不用。对于第四项,您试图输出projects[3].image[3],如果该图像数组只包含三个图像,则该数值不变。

如果要输出每个项目的所有三个图像,则还需要遍历各个图像。

0

需要在图像对象中指定图像url的索引。因为在你的代码的map函数中指定了增量数0到5(你的数据的长度)。但是你的图像数组没有map函数的索引值。

var Hello = React.createClass({ 
    render: function() { 
    return (
    <div> 
    { 
     ProjectAPI.all().map(function(item, index) { 
      return <img className="img" key={index} src={item.image[0]} /> 
     }) 
     } 
    </div> 
    ); 
    } 
});