forEach is not a function error with JavaScript array

Viewed 582597

I'm trying to make a simple loop:

const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
  console.log(child)
})

But I get the following error:

VM384:53 Uncaught TypeError: parent.children.forEach is not a function

Even though parent.children logs:

enter image description here

What could be the problem?

Note: Here's a JSFiddle.

13 Answers

You can check if you typed forEach correctly, if you typed foreach like in other programming languages it won't work.

Since you are using features of ES6 (arrow functions), you may also simply use a for loop like this:

for(let child of [{0: [{'a':1,'b':2},{'c':3}]},{1:[]}]) {
  console.log(child)
}

use JSON.parse()

str_json = JSON.parse(array);
str_json.forEach(function (item, index) {
    console.log(item);
});

You can use childNodes instead of children, childNodes is also more reliable considering browser compatibility issues, more info here:

parent.childNodes.forEach(function (child) {
    console.log(child)
});

or using spread operator:

[...parent.children].forEach(function (child) {
    console.log(child)
});

for object try this:

  Object.keys(yourObj).forEach(key => {
    console.log(key, yourObj[key]);
  });
Related