【问题标题】:How to loop over a json array and print the value without knowing the key in Ract Native?如何在不知道 Ract Native 中的键的情况下遍历 json 数组并打印值?
【发布时间】:2021-01-30 16:06:17
【问题描述】:

目前,我使用 map 来显示带有键名的值,但 JSON 会动态变化,因此我不会知道 JSON 数组的键。如何在不知道 JSON 密钥的情况下访问它?

我的 Json:(但密钥会有所不同)

{
  "records": [{
      "DATE": "15/10/2020",
      "AMT": "103284",
      "TAX": "8958",
      "TOTAL": "112242"
    },
    {
      "DATE": "16/10/2020",
      "AMT": "2336",
      "TAX": "209",
      "TOTAL": "2545"
    }
  ]
}

当前代码:

{
  sortedData && sortedData.length > 0 ?
    sortedData.map((item, index) => {
      return (
        <>
          <View style={{ flexDirection: 'row' }}>
            <View style={styles.container2}>
              <View style={styles.item}>
                <Text>{item.DATE}</Text>
              </View>
              <View style={styles.item2}>
                <Text>{item.AMT}</Text>
              </View>
              <View style={styles.item2}>
                <Text>{item.TAX}</Text>
              </View>
              <View style={styles.item2}>
                <Text>{item.TOTAL}</Text>
              </View>
            </View>
          </View>
          <Divider />
        </>
      );
    }) : false
}

我尝试了以下代码

【问题讨论】:

标签: json react-native react-native-android


【解决方案1】:

Object.keys 将为您提供对象的键,map 函数以数组格式返回键的所有值。

{Object.keys(sortedData).map(key => sortedData[key])}

这可能会有所帮助

<div>
  {arr.map(obj =>
    Object.entries(obj).map(([key, value]) => (
      <tr key={key}>
        <td>Key: {key}</td>
        <td>Activity Type: {value.activityType}</td>
        <td>DurationInSeconds: {value.durationInSeconds}</td>
      </tr>
    )))}
</div>

【讨论】:

  • 我无法在循环中使用 view 而不是您在里面使用的 sortedData[key]
  • 第二个循环打印 4 次,因为每行有 4 个键
  • 没错,你可以用这个实现你想要的输出?
  • 是的,我稍微修改了代码并且工作正常
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-16
  • 1970-01-01
  • 2021-07-19
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多