Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
194
rated 0 times [  200] [ 6]  / answers: 1 / hits: 22870  / 8 Years ago, wed, june 29, 2016, 12:00:00

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?


More From » for-loop

 Answers
16

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.


[#61586] Monday, June 27, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stacyl

Total Points: 131
Total Questions: 105
Total Answers: 94

Location: Egypt
Member since Tue, May 3, 2022
2 Years ago
stacyl questions
Thu, Jan 28, 21, 00:00, 3 Years ago
Sun, Mar 8, 20, 00:00, 4 Years ago
Tue, Feb 25, 20, 00:00, 4 Years ago
Tue, Feb 11, 20, 00:00, 4 Years ago
;