-1

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();
MortiestMorty
  • 635
  • 1
  • 5
  • 13

2 Answers2

2

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");
}
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • 2
    There was a another post where there was an argument over using === vs == and I did not realize I fat fingered it. ;) Thought that hold argument was coming to a new thread. (3.5 more hours until 5) – epascarello Jun 24 '16 at 17:33
1
in your condition if(functions[key] == 'foo')

the functions[key] returns a function. the key itself is already a literal that can be compare to 'foo'

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


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

functions.foo();