Created
June 20, 2019 18:54
-
-
Save guillaumegarcia13/f386b2f39475e6f4390516bd42ac8601 to your computer and use it in GitHub Desktop.
Recursively search object attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// From https://stackoverflow.com/questions/40603913/search-recursively-for-value-in-object-by-property-name | |
function findVal(obj, key) { | |
var seen = new Set; | |
var active = [obj]; | |
while (active.length) { | |
var new_active = []; | |
var found = []; | |
for (var i=0 ; i<active.length ; i++) { | |
Object.keys(active[i]).forEach(function(k) { | |
try { | |
var x = active[i][k]; | |
if (k === key) { | |
found.push(x); | |
} | |
else if (x && typeof x === "object" && !seen.has(x)) { | |
seen.add(x); | |
new_active.push(x); | |
} | |
} catch(e) { console.log('Impossible to access property', k, 'of', active[i]); } | |
}); | |
} | |
if (found.length) return found; | |
active = new_active; | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment