Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "forEach not a function" for this object?

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/

like image 383
haventchecked Avatar asked Jun 28 '15 05:06

haventchecked


People also ask

Why am I getting forEach is not a function?

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.

Can forEach be used on an object?

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.

Is forEach a method or function?

Definition and Usage. The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.

Is forEach functional?

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.


1 Answers

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"]

like image 195
TaoPR Avatar answered Sep 23 '22 13:09

TaoPR