如何迭代JS中的嵌套对象

时间:2020-07-28 12:09:55

标签: javascript firebase react-native

我将一些订单详细信息存储在firebase数据库中,当我从其中检索数据时,它显示如下内容。

Array [
  Object {
    "cartItems": Array [
      Object {
        "count": 1,
        "key": "1",
        "name": "EARRINGS",
        "pic": 20,
        "price": "200",
      },
      Object {
        "count": 1,
        "key": "2",
        "name": "Ring",
        "pic": 20,
        "price": "300",
      },
    ],
    "orderId": "OD4242JUL28",
  },
  Object {
    "cartItems": Array [
      Object {
        "count": 1,
        "key": "3",
        "name": "Staple",
        "pic": 20,
        "price": "400",
      },
      Object {
        "count": 1,
        "key": "2",
        "name": "Ring",
        "pic": 20,
        "price": "300",
      },
    ],
    "orderId": "OD4242JUL28",
  },
]

我可以通过使用[]中的索引来获取第一个或第二个对象,但是此后,如果在其上使用map函数,则无法对其进行迭代。我想检索每个cartItem并对其进行迭代以在订单部分中显示它。

FLATLIST

<FlatList 
          data={this.state.order}
          keyExtractor={(item) => item.key }
          showsVerticalScrollIndicator={false}
          renderItem={({item}) =>(
            <View>
                <Image source={item.pic} style={{width:width/2.05,height:150}} />
                <Text style={styles.text}>{item.cartItems.name}</Text>
                <Text style={styles.text}>{item.orderId}</Text>
          </View>
          ) }
        />

这仅返回orderID,但item.cartItems.name不返回任何内容。

2 个答案:

答案 0 :(得分:0)

@Lovepreet Singh尝试使用递归方法来迭代嵌套的对象数组。

答案 1 :(得分:0)

以某种方式我想出了以下代码

<FlatList 
          data={this.state.order}
          keyExtractor={(item) => item.key }
          // numColumns={2}
          showsVerticalScrollIndicator={false}
          renderItem={({item}) =>(
            <View>
                <Image source={item.pic} style={{width:width/2.05,height:150}} />
                <Text style={styles.text}>{item.cartItems.keys}</Text>
                {item.cartItems.map(val=>{
                  return(
                  <View>
                    <Text> {val.count} </Text>
                    <Text> {val.price} </Text>
                    <Text> {val.name} </Text>
                    <Text> {val.pic} </Text>
                    </View> )
                })}
                <Text style={styles.text}>{item.orderId}</Text>
          </View>
          ) }
        />

它在单位列表中使用了map函数,我相信这有一些错误,因为它会给出警告 Functions are not valid as a React child. 请指导我执行此操作的最佳方法。