Skip to content

Instantly share code, notes, and snippets.

@adrianhorning08
Created September 11, 2025 22:57
Show Gist options
  • Select an option

  • Save adrianhorning08/01ee797cb655b16789dd9aecce76bb67 to your computer and use it in GitHub Desktop.

Select an option

Save adrianhorning08/01ee797cb655b16789dd9aecce76bb67 to your computer and use it in GitHub Desktop.
Find Key in JS
// Function to recursively search for the key
export function findKey(obj, keyToFind) {
try {
if (obj.hasOwnProperty(keyToFind)) {
return obj[keyToFind];
}
for (let key in obj) {
if (typeof obj[key] === "object" && obj[key] !== null) {
let result = findKey(obj[key], keyToFind);
if (result !== undefined) {
return result;
}
}
}
return undefined;
} catch (error) {
console.log("error at findKey", error.message);
console.log("keyToFind", keyToFind);
throw new Error(error.message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment