10

How can I use forEach to loop an object?

For instance:

var dataset = {
    "data" : {
        "particles" : {},
        "no2" : {},
        "timestamp" : {}
    }
};

js:

dataset.data.forEach(function(field, index) {
    console.log(field);
});

error:

Uncaught TypeError: dataset.data.forEach is not a function

Any ideas?

Run
  • 54,938
  • 169
  • 450
  • 748
  • 3
    `forEach` is a `method` of `array`, not of `object`..Use `for-in` loop of `Object.keys(OBJECT).forEach` – Rayon Jun 29 '16 at 03:57
  • 1
    and also - http://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object – ThisClark Jun 29 '16 at 03:58
  • 2
    This has been answered before: http://stackoverflow.com/questions/14379274/javascript-iterate-object – BhathiyaW Jun 29 '16 at 03:59

1 Answers1

13

You need to use a for loop instead.for of or for in are good candidates .forEach is not going to work here...

const dataset = {
    "data" : {
        "particles" : {},
        "no2" : {},
        "timestamp" : {}
    }
};

// for in
for (const record in dataset.data) {
  if (dataset.data[record]) {
    console.log(record);
  }
}

// for of
for (const record of Object.keys(dataset.data)) {
  if (record) {
    console.log(record);
  }
}

You may have to do some additional work or provide a better explanation on what you're trying to solve if you want something more specific.

mwilson
  • 12,295
  • 7
  • 55
  • 95