0

Currently, I am using map to show the value with key name, but JSON will change dynamically so I won't be knowing the key for the JSON array. How to access it without knowing the key of the JSON?

My Json: (But the keys will be varying)

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

Current code:

{
  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
}

I tried the below code enter image description here

Derek Wang
  • 10,098
  • 4
  • 18
  • 39
Prajna
  • 578
  • 4
  • 8
  • 23
  • 1
    Does this answer your question? [Accessing Object values without knowing the keys of that Objects](https://stackoverflow.com/questions/50933104/accessing-object-values-without-knowing-the-keys-of-that-objects) – Smile Oct 16 '20 at 06:31
  • I tried the first answer to the question that you mentioned, but syntax error :( – Prajna Oct 16 '20 at 06:43

1 Answers1

1

Object.keys will give you keys of object and map function returns all the values of the key in a array format.

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

This might help

<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>
Nooruddin Lakhani
  • 7,507
  • 2
  • 19
  • 39