JSON-Loop icon indicating copy to clipboard operation
JSON-Loop copied to clipboard

forEach is not a function error with JavaScript array [Solution Included]

Open Hydra9268 opened this issue 6 years ago • 3 comments

There are four areas in the this code where the following throws a forEach. It is not a function because parent.children is not an array. Instead, it is an HTMLCollection and as such doesn't have forEach method.

obj[that.children].forEach(function(child) {
     that.countNodes(child);
});

Here's the fix:

Array.from(that.children).forEach(function (child) {
     that.countNodes(child);
});

Tested and works in the latest version of jQuery (3.4.1, at the time of this writing).

Hydra9268 avatar Sep 17 '19 17:09 Hydra9268

([...that.children]).forEach(child=>child)

stangrinn avatar Feb 26 '20 09:02 stangrinn

The parent.children is an Array like object. It is NodeList type, which is an Array like object because:

It contains the length property, which indicates the number of nodes Each node is a property value with numeric name, starting from 0: {0: NodeObject, 1: NodeObject, length: 2, ...}

It is a case where your data response looks like an array but it is an Object. Object does not have forEach, it belongs to Array prototype. If you want to JavaScript iteration 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]);
});

If you have access to the API you're connecting to you can ensure the response it sends out is an array but if not simply parsing the data response using JSON.parse() should do the trick.

markfilan avatar Feb 01 '22 04:02 markfilan