I have a object
var foo = { jon : {age: 'old', feeling: 'sad' },
jack: {age: 'young', feeling: 'happy'}
};
The members of foo are created dynamically; as is the object bar.
var bar = { name: 'jon' };
I would like to to see if jon is a member of foo. I must be doing something terribly wrong.
function isMember(bar) {
for(prop in foo) {
if (foo[prop] === bar.name){
return true;
break;
}
}
return false;
};
always returns true!!
Here's a working version of the above:
foo = { jon : {age: 'old', feeling: 'sad' },
jack: {age: 'young', feeling: 'happy'}
};
bar = { name: 'jon' };
function isMember(bar) {
for(prop in foo) {
console.log([prop, foo[prop], bar.name, ]);
if (prop === bar.name){
return true;
}
}
return false;
};
console.log(['ismember', isMember(bar)]);
Live example:
Try changing bar.name
to e.g. jon1
to see how it behaves. Take a look at your console window to see what it outputs, that will help you understanding what it does exactly and where you went wrong.
Hope this helps.