2017-10-21 41 views
1

我試圖顯示基於其對象之一的變體項目列表。請參閱下面的代碼的一些見解:在React Native中映射嵌套的對象陣列

data: [{ 
 
    "transportation": [ 
 
    {"id": "1", "name": "bus", "type": "large"}, 
 
    {"id": "2", "name": "bicycle", "type": "small"}], 
 
    
 
    "animal": [ 
 
    {"id": "3", "name": "elephant", "type": "large"}, 
 
    {"id": "4", "name": "mouse", "type": "small"}] 
 
}]

對於上面的例子,我想顯示可以說一些簡單的像「大」的文字,如果類型是「大」和「小「文字如果類型是」小「,我首先想到的是做一個嵌套地圖(數據的外部地圖,運輸/動物的內部地圖)我首先測試內部地圖,而不使用外部地圖,如下圖所示:

data.animal.map((info) => { 
 
    switch (info.type){ 
 
    case "large": 
 
     return(
 
     <View> 
 
     <Text>Large</Text> 
 
     </View>); 
 

 
    case "small": 
 
     return(
 
     <View> 
 
     <Text>Small</Text> 
 
     </View>); 
 
      
 
    default: 
 
     return(
 
     <View> 
 
     <Text>Whatever</Text> 
 
     </View>); 
 
    } 
 
})

TypeError: Cannot read property 'map' of undefined

任何想法,爲什麼會出現這種情況?

編輯:

我曾試圖做一個嵌套循環在等待一個答案。下面是我的代碼片段:

data.map((category, key) => { 
 
    return(
 
    Object.keys(category).map((info) => { 
 
    switch (info.type){ 
 
    case "large": 
 
    return(
 
    <View> 
 
    <Text>Large</Text> 
 
    </View>); 
 
    
 
    case "small": 
 
    return(
 
    <View> 
 
    <Text>Small</Text> 
 
    </View>); 
 
    
 
    default: 
 
    return(
 
    <View> 
 
    <Text>Whatever</Text> 
 
    </View>); 
 
} 
 
    }) 
 
) 
 
})

它運行沒有錯誤,但它並沒有給我預期的結果。所有的輸出都切換爲默認值,即「無論」。

回答

1

您正在訪問數據數組的第一個對象。所以,你的代碼應該是

data[0].animal.map((info) => { 
.... 
0

data = [{ 
 
    "transportation": [ 
 
    {"id": "1", "name": "bus", "type": "large"}, 
 
    {"id": "2", "name": "bicycle", "type": "small"}], 
 
    
 
    "animal": [ 
 
    {"id": "3", "name": "elephant", "type": "large"}, 
 
    {"id": "4", "name": "mouse", "type": "small"}] 
 
}] 
 

 

 
data[0].animal.map((info) => { 
 
    return console.log(info) 
 
    } 
 
)