Object doesn't support property or method 'forEach' IE 11

Viewed 5119

I have below snippet

data.forEach(function (row) {
var dataRow = [];

columns.forEach(function (column) {

dataRow.push(row[column].toString());
})

which is giving me error data.forEach(function (row) { .What should be alternate to this? How to resolve it?

2 Answers

For anyone using document.querySelectorAll('..').forEach() and having this issue in IE 11 saying "forEach is not a function", I found a hack on reddit which worked nicely:

if (typeof NodeList.prototype.forEach !== 'function')  {
    NodeList.prototype.forEach = Array.prototype.forEach;
}

This works perfectly and is 3 lines of code instead of a polyfill.

@JoeTaras hinted at this in his answer (yes IE does have Array.forEach since IE9), but I still think my answer adds value and will help other users.

IE11 knows forEach statement (is IE compliant from IE 9.0, see here), but if you want you can use instead of forEach you can use for statement, as follow:

I've edited my answer, add a check on data object if is an array

if (data != null && Array.isArray(data)) {
    var dataRow = [];
    for (var i = 0; i < data.length; i++) {
        var row = data[i];
        for (var j = 0; j < columns.length; i++) {
            var column = columns[i];

            dataRow.push(row[column].toString());
        }
    }
}
Related