sveti petar
sveti petar

Reputation: 3797

Error says "object is null" if one the object's properties is null

I have a slight problem in Javascript with objects being handled in a strange (to say the least) way, unless I'm missing something.

I have an object named state. When I do console.log(state) I get this:

see image please

At this point, I try to go through the object using jQuery's each:

$.each(state, function (i, sobj) {
        if(mid == sobj.user_id)
            //some stuff;
    });

However, here I get an error saying TypeError: sobj is null. I found that this is because the trump property within the object (see image above) is initialized to null. With any other value, it works. Obviously I can fix this by initializing it to 0 or something, but this is bugging me on a conceptual level: why shouldn't one of the properties be allowed to have null as its value? It doesn't make sense to me that I should get an error saying the whole object is null when I loop through it like this, just because one of the properties is null. I didn't try to do anything with the property specifically.

So, can someone tell me why this is happening (Google doesn't help) and if there's a way to fix it besides the obvious "don't let anything be null within an object"?

Upvotes: 0

Views: 546

Answers (2)

S. A.
S. A.

Reputation: 3754

It seems you only want to iterate over the objects inside the state object. You could check if the item is an object.

$.each(state, function (i, sobj) {
    if(typeof(sobj) == "object" && mid == sobj.user_id)
        //some stuff;
});

Upvotes: 1

El Kabong
El Kabong

Reputation: 717

You're iterating over the entire object like it's a collection of objects - meaning that trump in this case is an object, not a property of an object(state). You either need to iterate only over the collection of objects in state, or test that the object isn't null before you look for a property value:

if(typeof(sobj) != 'undefined'){
    if(mid == sobj.user_id)
            //some stuff;
}

Upvotes: 1

Related Questions