Search code examples
javascriptloopsobject-literalfor-in-loop

Looping through object literal with nested functions


I'm trying to loop through an object literal and select just one of the keys and return it's value, which will be a function. My problem is, that I can't get the loop to return just one value - it always returns all of the values (functions). I noticed that if I nest the function inside of the object literal (see foo), then it works better, but still not looping through.

Here is the JS fiddle.

var functions = {
   blah: blah(),
   foo: function() { console.log("foo"); }
};


for(var key in functions){
   if(functions[key] == 'foo') {
   console.log("hello"); //if functions contains the key 'foo' say hi
  }
}
function blah () {alert("blah")};

functions.foo();

Solution

  • You are not checking for the key, you are checking a string against a function.

    for(var key in functions){
        if (key==="foo") {
            console.log("hello");
        }
    }
    

    another way is to use Object.keys()

    var keys = Object.keys(functions);
    if (keys.indexOf("foo")>-1) {
        console.log("hello");
    }