-2

I use console.log(responseJSON) and it prints this logs to screen as below code. So I want to print only latlng and when I try to console.log(responseJSON.markers.latlng) or with console.log(responseJSON.markers) then it prints undefined.

Array [
Object {
  "markers": Object {
    "index": "1",
    "latlng": Object {
      "latitude": "40.3565",
      "longitude": "27.9774",
    },
  },
},
Object {
  "markers": Object {
    "index": "3",
    "latlng": Object {
      "latitude": "40.3471",
      "longitude": "27.9598",
    },
  },
},
Object {
  "markers": Object {
    "index": "2",
    "latlng": Object {
      "latitude": "40",
      "longitude": "27.9708",
    },
  },
},]

How can I print and get data printed e.g. with:

console.log(responseJSON.markers.latlng);
Engin Yilmaz
  • 393
  • 1
  • 5
  • 17
  • 1
    Your response is an array, not a single object. `responseJSON[0].markers` will work. – Máté Safranka Apr 21 '18 at 11:30
  • 1
    That's not [JSON](http://json.org). _"JSON is a textual, language-indepedent data-exchange format, much like XML, CSV or YAML."_ - [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Apr 21 '18 at 11:40

2 Answers2

3

The response is an array. You have to use an index to get to each of the elements of the array.

For instance responseJSON[0].markers.latlong, and so on.

1

You can access the inner contents of an array of object with simple forEach loop

var responseJSON= [
 {
  "markers":  {
    "index": "1",
    "latlng":  {
      "latitude": "40.3565",
      "longitude": "27.9774",
    },
  },
},
 {
  "markers":  {
    "index": "3",
    "latlng":  {
      "latitude": "40.3471",
      "longitude": "27.9598",
    },
  },
},
 {
  "markers":  {
    "index": "2",
    "latlng":  {
      "latitude": "40",
      "longitude": "27.9708",
    },
  },
},];

responseJSON.forEach(function(currentElement){
   console.log(currentElement.markers.latlng)
})
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103