Patrick
Patrick

Reputation: 241

jQuery .forEach() causing error, "undefined is not a function"

I'm getting the error, undefined is not a function for the line entries.forEach(function(e) { and I don't know why. Can anyone help?

I'm certain that entries is defined as the prototype below when I pass it to the function.

This is the function I'm working on:

function score_relevance3(entries, usr_tags) {

    entries.forEach(function(e) 
    {
        entries[e].count = 0;
        entries[e].tags.forEach(function(i) 
        {
            usr_tags.forEach(function(f) 
            {
                if (entries[e].tags[i] === usr_tags[f]) 
                {
                    entries[e].count++;
                }
            });
        });
    });

    return entries;
}

Here is a prototype of my entries object:

entries = {
"1":{"tags":["1","2"]},
"2":{"tags":["1","3","2"]},
"3":{"tags":["1","2"]},
"4":{"tags":["1","2"]},
"5":{"tags":["1","2"]},
"6":{"tags":["4","5","6","2"]},
"7":{"tags":["4","7"]},
"8":{"tags":["4","8","3"]},
"9":{"tags":["4","9"]}
};

Upvotes: 1

Views: 4847

Answers (2)

lhoworko
lhoworko

Reputation: 1191

Like elclanrs mentions in the comment, you can't call forEach on an object, only an array. If you want to go through entries, use:

for (entry in entries) { ...

Upvotes: 2

Lajos Arpad
Lajos Arpad

Reputation: 76482

The reason is simple. For instance, if you have an object, foo, and you try to call foo.bar(), then, if bar is undefined, then you cannot use it as a function and you will get the error of

undefined is not a function

Here

entries.forEach(function(e) {

I believe forEach does not exist and you have the error for the above mentioned reasons. Try this:

console.log(entries.forEach);

Is it undefined?

Upvotes: 0

Related Questions