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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With