Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'd like to console.log() an object and do a search for a particular value within that object. Is this possible?

Note: the object that I'm trying to search is humongous and multi-dimensional, so expanding each field and doing a simple Ctrl+F find isn't ideal.

like image 995
dmathisen Avatar asked Jun 26 '13 17:06

dmathisen


People also ask

How do I see variable values in Chrome console?

To view any variable in chrome, go to "Sources", and then "Watch" and add it. If you add the "window" variable here then you can expand it and explore.

How do you search for something on Inspect Element?

Just right-click and click Inspect Inspect Element, or press Command+Option+i on your Mac or F12 on your PC. In the search field, you can type anything—ANYTHING—that you want to find on this web page, and it will appear in this pane.


1 Answers

The code below adds something like what you're looking for to the console object as

console.logSearchingForValue

Breadth-first search, matching on equivalent "JSON" value, handling NaNs correctly, returning multiple locations, and making numeric index expressions not quoted are left as exercises to the reader. :)

It is already really easy to swap in different definitions of equality.

var searchHaystack = function(haystack, needle, path, equalityFn, visited) {    if(typeof haystack != "object") {     console.warn("non-object haystack at " + path.join("."));   }    if(visited.has(haystack))     return [false, null];    for(var key in haystack) {     if(!haystack.hasOwnProperty(key))       continue;      if(equalityFn(needle, haystack[key])) {       path.push(key);       return [true, path];     }      visited.add(haystack);     if(typeof haystack[key] == "object") {       var pCopy = path.slice();       pCopy.push(key);       var deeper = searchHaystack(haystack[key], needle, pCopy, equalityFn, visited);       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 visited = new Set();    var strictEquals = function(a,b) { return a === b; };    var result = searchHaystack(haystack, needle, ["<haystack>"], strictEquals, visited);    if(result[0]) {       this.log("Found it!");       this.log(pathToIndexExpression(result[1]));    }    else {       this.log("didn't find it");    } } 
like image 90
ellisbben Avatar answered Sep 28 '22 21:09

ellisbben