Skip to content

Instantly share code, notes, and snippets.

@guillaumegarcia13
Created June 20, 2019 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guillaumegarcia13/f386b2f39475e6f4390516bd42ac8601 to your computer and use it in GitHub Desktop.
Save guillaumegarcia13/f386b2f39475e6f4390516bd42ac8601 to your computer and use it in GitHub Desktop.
Recursively search object attributes
// 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