Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native loop with map

I'm developing an app in React Native and I have this JSON:

const places = {
  "place1":{
    "title":"title 1",
    "image":"../img/image1.jpeg",
    "description":"description 1.",
  },
  "place2":{
    "title":"title 2",
    "image":"../img/image2.jpeg",
    "description":"description 2.",
  }
}; 

I'd like to output it in a list of elements, I understood that to do this I have to use map() this is my code:

export default class App extends Component{
  render() {
    return (
      <View style={styles.container}>
        {places.map((place) => {
            return (
              <Text>{place.title}</Text>
              <Text>{place.description}</Text>
            )
         })}
      </View>
    );
  }
}

but it does not work, does anyone know what I'm wrong or how can I reach my goal?

like image 594
V.Cozzatella Avatar asked Oct 30 '18 11:10

V.Cozzatella


2 Answers

Places is an object and you can't iterate like this. You have to get the keys with Object.keys and iterate through them instead. Like this.

Object.keys(places).map((key) => {
    return (
      <Text>{places[key].title}</Text>
      <Text>{places[key].description}</Text>
    )
 })}
like image 68
Alex G Avatar answered Oct 01 '22 16:10

Alex G


MAP function works on Array, not on object. Please update your const places as the following:

const places = [{
  "title":"title 1",
  "image":"../img/image1.jpeg",
  "description":"description 1.",
},{
 "title":"title 2",
 "image":"../img/image2.jpeg",
 "description":"description 2.",
}]

Thanks. Enjoy Coding.

like image 42
Rohan Kangale Avatar answered Oct 01 '22 17:10

Rohan Kangale