ZeMoon
ZeMoon

Reputation: 20274

Error calling forEach on array

I am getting a problem forEach within anoter forEach function:

The results variable contains an object like:

{
    names: [
        'Someone',
        'Someone else'
    ],
    emails: [
        '[email protected]'
        '[email protected]'
    ]
}

I want it to unwind all the arrays and result in an array like this:

[
    {term: 'Someone', type: 'names'},
    ...
]

Here is my code:

var keys = _.keys(results);

console.log(keys);

var finalResult = [];

keys.forEach( function (key) {

    var arrTerms = results[key];

    console.log(key, arrTerms); //arrTerms prints fine

    arrTerms.forEach(function (term) { //This line throws an exception

        finalResult.push({
            term: term,
            type: key
        });
    });

});

The nested call to forEach throws the following exception:

TypeError: Uncaught error: Cannot call method 'forEach' of undefined

I tried using a for loop with iteration till length, but it generated another exception:

TypeError: Uncaught error: Cannot read property 'length' of undefined

Upvotes: 1

Views: 13280

Answers (1)

OddDev
OddDev

Reputation: 3734

I think the problem here is that you may assign undefined to your arrTerms (when results[key] returns undefined cause you take a key which isn't contained in your object). Try to do this:

var keys = _.keys(results);

console.log(keys);

var finalResult = [];

keys.forEach( function (key) {
    if(results[key] != undefined){
     var arrTerms = results[key];

     arrTerms.forEach(function (term) { //This line throws an exception
        console.log(key, arrTerms); //arrTerms prints fine
        finalResult.push({
            term: term,
            type: key
        });
     });
    }
});

Upvotes: 1

Related Questions