Omer Guttman
Omer Guttman

Reputation: 141

Iterating over a jsonlike object

I am pretty new to java script (and react/react-native in general), i received an object threw an API and converted the response to JSON, the object is formatted like this:

{name1: {…}, name2: {…}, name3: {…}, name4: {…},...}

when each {...} contains "data": number how can i iterate over all possible results and display (preferably in a flatlist) the info like this name (i)->number (i)

i don't imagine it being much help but this is what i have so far

 return(
  <View>
    <FlatList
      data={this.state.res}
      renderItem={({item}) => <Text>{item.currentVotes}</Text>}
      keyExtractor={({id}) => id}
    />
  </View>

Upvotes: 2

Views: 54

Answers (2)

Jaydeep Galani
Jaydeep Galani

Reputation: 4961

To iterate through Objects you need to get an array of all keys of that Object and finally iterate from that array.

like this, you can get all keys using single line

let data = {name1: {…}, name2: {…}, name3: {…}, name4: {…},...};
let keys = Object.keys(data);

and to iterate through array simply use map function,

keys.map(item=>
<View>
  <Text>{data[item]}</Text>
</View> 
)

Upvotes: 0

Omer Guttman
Omer Guttman

Reputation: 141

this is the answer i came up with, its not prefect but it works

var resScreen = []
res=this.state.res
for(a in res){
  resScreen.push(
    <View>
      <Text>{a},{this.state.res[a].currentVotes}</Text>
    </View>
  )
}
return resScreen

Upvotes: 1

Related Questions