0

I have an ajax request which loads a JSON file and parses it by storing a reference to the object. I'm trying to find a way in which I can loop through the object but due to it's structure I get errors on the console.

Here is an example of the JSON that I am parsing:

{
  "markers": {
    "marker": [
      {
        "name": "john",
        "latitude": "53.4682282",
        "longitude": "-2.238547"
      },
      {
        "name": "david",
        "latitude": "53.4663409",
        "longitude": "-2.2328164"
      },
      {
        "name": "mathew",
        "latitude": "53.4668135",
        "longitude": "-2.2310998"
      }
    ]
  }
}

I have tried the following js loop, but I can't seem to get it to work correctly. (N.B. the object retrieved from parsing the JSON is referenced as markers.

markers.forEach(function(marker) {
  console.log(marker.name);
});

4 Answers 4

1

markers is an object that contain the array marker. You need to iterate marker

var obj = {
  "markers": {
    "marker": [{
        "name": "john",
        "latitude": "53.4682282",
        "longitude": "-2.238547"
      },
      {
        "name": "david",
        "latitude": "53.4663409",
        "longitude": "-2.2328164"
      },
      {
        "name": "mathew",
        "latitude": "53.4668135",
        "longitude": "-2.2310998"
      }
    ]
  }
}

obj.markers.marker.forEach(m => console.log(m.name));

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, this helped me solve the problem. I will post the correct answer now
0

Try this:

markers.marker.forEach(function(marker) {
  console.log(marker.name);
});

2 Comments

I have, my console gives me TypeError: markers.marker is undefined
Because you should firstly take you object and push property "markers" from it to the variable with name "markers".
0

I needed to access the object inside the object. i.e.,

markers.markers.marker.forEach(function(marker) {
    console.log(marker.name);
});

1 Comment

I already post the answer which exactly solve your problem. You don't have to post an answer yourself. You can simply accept mine
0

Try this:

'markers.marker.map((ma) => { console.log(ma.name); });`

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.