简体   繁体   中英

Looping through an Object containing an Array of Objects in JS

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. (NB the object retrieved from parsing the JSON is referenced as markers .

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

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)); 

Try this:

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

I needed to access the object inside the object. ie,

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

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM