2017-07-14 63 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> 
    ); 
    } 
});