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?

3

1 Answer 1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.