1

I am trying to print out array's value, converting into string in the description of mapview marker. when I put <Text>nameList</text> inside of return() under <View style={styles.container}> is okay, but description={nameList.toString()} in is just print out {object,object}, {object,object}, {object,object}

Please let me know how would I solve.

constructor(){
super()
this.state = {name: []}

}

  componentDidMount(){

   return fetch('https://transportapi.com/v3/uk/bus/stop/6090282/live.jsonapp_id=8425e834&app_key=a9de6fe50081ecf38d2e9c9d5f1a87e0&group=route&nextbuses=yes')
.then((response) => response.json())
.then((responseJson) => {
for(var x in responseJson.departures){
this.setState({ 
state : this.state["name"].push(responseJson.departures[x][0])

});
}



   })
.catch((error) => {
  console.error(error);
});
  }




render() {


const info = this.state.name;
const nameList = info.map(name =>{
  return(

    <Text key={name.line}>{name.line}{name.aimed_departure_time}</Text>
  ) 

})

 return (

  <View style={styles.container}>
    <MapView
initialRegion={{
  latitude: 37.78825,
  longitude: -122.4324,
  latitudeDelta: 0.0922,
  longitudeDelta: 0.0421,
}}
>

  <MapView.Marker
   coordinate={{
   latitude: 37.78825,
  longitude: -122.4324,
   }}
   title={'Hello'}
   description={nameList.toString()}

   />

    </MapView>

 </View>

 }
5
  • Do you want to have multiple markers with an invidual title/description? Commented Dec 5, 2017 at 11:59
  • no need multiple markers, but just display something like {{name.line},{name.aimed_departure_time}} , {{name.line},{name.aimed_departure_time}} Commented Dec 5, 2017 at 12:53
  • You made nameList a Text Component and it’s inner text content can’t be extracted using .toString(). Use a string instead, see Vipin’s edited answer below for a solution Commented Dec 5, 2017 at 13:39
  • You mean const nameList should be var nameList = info.map (......? Commented Dec 5, 2017 at 13:46
  • @DHC You can return a string in the nameList map and then use nameList.join(',') to create a full string from the array. Commented Dec 5, 2017 at 14:28

1 Answer 1

14

Use

JSON.stringify(nameList)

instead of

nameList.toString()

Source: https://www.w3schools.com/js/js_json_stringify.asp

Edited

Change your map to

const nameList = info.map(name => {
  return `${name.line} : ${name.aimed_departure_time}`
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.