Created
September 11, 2025 22:57
-
-
Save adrianhorning08/01ee797cb655b16789dd9aecce76bb67 to your computer and use it in GitHub Desktop.
Find Key in JS
This file contains hidden or 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
| // 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