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.
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.
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.
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"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With