Languages

JavaScript - why is forEach not a function for this object?

0 points
Asked by:
Nathanial-Donald
584

JavaScript keeps throwing me this error:

When I try to do something like:

Why is that so?

1 answer
0 points
Answered by:
Admin Dirask Community
4380

Objects don't have forEach() method, it can be only used with arrays.

However, since ES8 (ECMAScript 2017) there is Object.values() method that returns array of the object's values. You can use it to create array of values and then iterate it with forEach().

Practical example

Alternative solution

As an alternative for older versions of JavaScript, you can use Object.keys() method that returns array of the object's keys and then use array notation to get values.

 

References

  1. Array.prototype.forEach() - JavaScript | MDN
  2. Object.values() - JavaScript | MDN
  3. Object.keys() - JavaScript | MDN
0 commentsAdd comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join