0

I'm receiving data from a controller that looks like this when I console.log:

{1: {…}, 2: {…}, 3: {…}}

1: {datasetID: 1, title: "Adirondack Trout Survey", year: "2015", ADD-startYr: "2015", ADD-endYr: "2015", …}

2: {datasetID: 2, title: "Adirondack Trout Survey", year: "2016", ADD-startYr: "2016", ADD-endYr: "2016", …}

3: {datasetID: 3, title: "Adirondack Trout Survey", year: "2017", ADD-startYr: "2017", ADD-endYr: "2017", …}

I'm trying to access the datasetIDs and this was my attempt:

 $(data).each(function(i, d){
     console.log(d.datasetID);
}

But I am getting undefined returned. I'm not sure how to loop through that object and get the dataset IDs?

Thanks!

D. Pardal
  • 6,173
  • 1
  • 17
  • 37
xanabobana
  • 63
  • 2
  • 16

4 Answers4

1

Try to use:

$.each( data, function(i, d) {
  console.log(d.datasetID);
});

Output will be:

1
2
3
Ivan Vasechko
  • 276
  • 1
  • 2
  • 6
0

You're using $(data).each but what you want is $.each (docs), with the same callback code.

Zac Anger
  • 6,983
  • 2
  • 15
  • 42
  • 1
    I thought the same, but it doesn't: https://jsfiddle.net/RoryMcCrossan/9gqaz4pd/. That said, I'd prefer the use of `forEach()` over needlessly including jQuery to loop through a JS structure, but this does work. – Rory McCrossan Jan 08 '21 at 16:24
  • They're different functions for different use-cases. `$.each` is a generic iterator; `$(selector).each` is for iterating over jQuery objects with DOM elements. See the respective docs: https://api.jquery.com/each/ and https://api.jquery.com/jQuery.each/ – Zac Anger Jan 08 '21 at 16:24
0
let data = {1: {datasetID: 1, title: "Adirondack Trout Survey"}, 2: {datasetID: 2, title: "Adirondack Trout Survey"}, 3: {datasetID: 3, title: "Adirondack Trout Survey"}}

it's an object with indexed props access like this

for (const index in data) {
      console.log(data[index].datasetID);
    }
Zack Heisenberg
  • 499
  • 6
  • 12
0

Quick answer: you're using the wrong jQuery "each" method.

Instead of:

$(myObject).each(function(i, d) // ...

What you want is:

$.each(myObject, function(key, val) // ...

Complete code:

$.each(data, function(key, val){
  console.log(val.datasetID); // val, in this case, is your nested object
});

See the differences from the docs:

Vanilla version

You can also do this without jQuery, by using the Object.keys method like so:

Object.keys(myObject).forEach(function(key) {
  var val = myObject[key];

  // ... do the things ...

});

Just make sure you have browser support for it.

Cheers!

bmdev
  • 386
  • 1
  • 7