Search code examples
javascriptobjectdynamicpropertiesmembership

JavaScript: How to iterate over properties of an object and test against a dynamic property of another object


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!!


Solution

  • 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.