Skip to content

Instantly share code, notes, and snippets.

@sebgeelen
Created July 31, 2020 08:03
Show Gist options
  • Save sebgeelen/bd60f43379edeb503624c4c9c9c17bfa to your computer and use it in GitHub Desktop.
Save sebgeelen/bd60f43379edeb503624c4c9c9c17bfa to your computer and use it in GitHub Desktop.
Discover key in js object
let cache = new Set();
let discoverIn = function(obj, keyToFind, previousPath = "") {
if(obj === null || typeof obj !== "object") {
return;
}
if (cache.has(obj)) return;
cache.add(obj);
const keys = Object.keys(obj);
for (let k of keys) {
// ignore __ leading keys
if (k.startsWith('__')) continue;
if (k === keyToFind) {
console.log("path : ", previousPath + "." + k);
break;
}
discoverIn(obj[k], keyToFind, previousPath + "." + k);
}
}
discoverIn(form, "keytofind");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment