0

I'm unable to access value's from a state array filled with objects.

I got the values when I stored them in an array, but when I try to console.log the state, it prints out: [Object Object]. I have tried the following to get the value, example:

var data=[{"coordinate":{"longitude":73.8679075241089,"latitude":18.515422222637756},"key":0,"color":"#ffc130"}];

console.log("data"+data[0].coordinate.longitude);

This is how I tried to get the value in React Native:

    console.log("location "+JSON.stringify(this.state.markers));
    var data=JSON.stringify(this.state.markers);
    console.log("datamap"+JSON.parse(data));
    var dataparse = JSON.parse(data);
    console.log("data parse "+this.state.markers[0].coordinate.latitude);

This is where I declared the array:

class DefaultMarkers extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      region: {
        latitude: LATITUDE,
        longitude: LONGITUDE,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
      },
      markers: [],
    };
  }

I want to store the latitude and longitude in an array.

2
  • this.state.markers[0].coordinate.latitude should work if data in your first snippet corresponds to markers. Please create a Minimal, Complete, and Verifiable example in e.g. Snack so that it will be easier for someone to help you. Commented Mar 26, 2019 at 12:33
  • I already tried this.state.markers[0].coordinate.latitude @Tholle but i get the error object not found and yes I'll create an example in snack . Commented Mar 28, 2019 at 6:37

2 Answers 2

1

I used JSON.parse() and JSON.stringify() to parse it

const data = JSON.parse(JSON.stringify(this.state.markers));
Sign up to request clarification or add additional context in comments.

Comments

0

Change your console.log, separate two values with the comma instead concatenating them.

Change from

console.log("location "+JSON.stringify(this.state.markers));

To

console.log("location ", JSON.stringify(this.state.markers));

Hope you will be able to print the value.

1 Comment

The problem is not consoling the value I need to parse it to get the coordinates.

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.