This is probably something really dumb, but I don't understand why this doesn't work.
var a = {"cat":"large"}; a.forEach(function(value, key, map){ console.log(value); });
Uncaught TypeError: a.forEach is not a function
http://jsfiddle.net/ty7z6pse/
The "forEach is not a function" error occurs when we call the forEach() method on a value that is not of type array, Map , or Set . To solve the error, make sure to only call the forEach method on arrays, Map or Set objects.
JavaScript's Array#forEach() function lets you iterate over an array, but not over an object. But you can iterate over a JavaScript object using forEach() if you transform the object into an array first, using Object.
Definition and Usage. The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.
forEach is what functional programmers call a higher-order function. Nothing complicated either; it's just a function responsible for running or returning other functions.
Object does not have forEach
, it belongs to Array
prototype. If you want to iterate through each key-value pair in the object and take the values. You can do this:
Object.keys(a).forEach(function (key){ console.log(a[key]); });
Usage note: For an object v = {"cat":"large", "dog": "small", "bird": "tiny"};
, Object.keys(v)
gives you an array of the keys so you get ["cat","dog","bird"]
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