Reputation: 3797
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:
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
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
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