Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript forEach - how to loop an object? [duplicate]

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?

like image 832
Run Avatar asked Jun 29 '16 03:06

Run


1 Answers

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.

like image 198
mwilson Avatar answered Oct 19 '22 18:10

mwilson