Search code examples
javascriptobject

Object search works first time only


I created an object called "Jarz". Then added an object within it called 'cat'. Then I made a function to search within the Jarz object for an object called 'cat', which works. However for every object after 'cat' that I add to 'Jarz' the function will not find it in the search. Only the first run ever works. Here is the code:

var Jarz = {};

Jarz['cat'] = {};  

Here is the function:

function doesObjExist(ObjName){
var tmpArr = Object.keys(Jarz);
for(var i = 0; i < tmpArr.length; i++){
    if(tmpArr[i] === ObjName){
        return true;
    }

    else {
        return false;
    }
}
}

When I run it on the first object 'cat' it returns true. But any obj I make after that returns false. ie:

Jarz['hat'] = {};
doesObjExist('hat')  // returns false

I cant seem to find what is missing here. Any help is appreciated, thanks.


Solution

  • It's because when you call it with hat, it is checking first for cat as it is false your returning from the loop so it won't execute further to check for hat.

    Change this to:

    var Jarz = {};
    
    Jarz['cat'] = {};
    console.log(doesObjExist('cat'));
    Jarz['hat'] = {};
    console.log(doesObjExist('hat'));
    
    function doesObjExist(ObjName) {
      var tmpArr = Object.keys(Jarz);
      var count = 0;
      for (var i = 0; i < tmpArr.length; i++) {
        if (tmpArr[i] === ObjName) {
          return true;
        } else {
          count++;
        }
      }
      if (count >= tmpArr.length)
        return false;
    }