繁体   English   中英

如何在 JS 中遍历嵌套对象

[英]How to iterate over nested objects in JS

我在 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",
  },
]

我可以通过在 [] 中使用索引来获得第一个或第二个 object,但在那之后,如果我在其上使用 map function,我将无法对其进行迭代。 我想检索每个 cartItem 并对其进行迭代以在订单部分显示它。

平面列表

<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返回任何内容。

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

不知何故,我想通了下面的代码

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM