RsD0p9BK
10/7/2014 - 12:32 PM

search_in_console.js

// Is there a way to search a console logged object for particular values in Chrome DevTools?

var searchHaystack = function(haystack, needle, path, exactEquals) {

   //dumb truthiness handling
   exactEquals = exactEquals ? true : false;

   if(typeof haystack != "object") {
      console.warn("non-object haystack at " + path.join("."));
      return [false, null];
   }
   for(var key in haystack) {
      if(!haystack.hasOwnProperty(key))
         continue;

      var matches;
      //might be good to have a "JSON-equivalent" option too...
      if(exactEquals)
         matches = haystack[key] === needle;
      else
         matches = haystack[key] == needle;

      if(matches) {
         path.push(key);
         return [true, path];
      }

      if(typeof haystack[key] == "object") {
         var pCopy = path.slice();
         pCopy.push(key);
         var deeper = searchHaystack(haystack[key], needle, pCopy, exactEquals);
         if(deeper[0]) {
            return deeper;
         }
      }
   }
   return [false, null];
}

var pathToIndexExpression = function(path) {
   var prefix = path[0];
   path = path.slice(1);
   for(var i = 0; i < path.length; i++) {
      if(typeof path[i] == "string")
         path[i] = "\"" + path[i] + "\"";
   }
   return prefix + "[" + path.join("][") + "]"
}

console.logSearchingForValue = function(haystack, needle) {
   this.log("Searching");
   this.log(haystack);
   this.log("for");
   this.log(needle);
   var result = searchHaystack(haystack, needle, ["<haystack>"], true);
   if(result[0]) {
      this.log("Found it!");
      this.log(pathToIndexExpression(result[1]));
   }
   else {
      this.log("didn't find it");
   }
}

// http://stackoverflow.com/questions/17326939/is-there-a-way-to-search-a-console-logged-object-for-particular-values-in-chrome