Created
March 12, 2024 09:16
-
-
Save upalexgill/c520e33d5da5650be5c1bb87a985a96d to your computer and use it in GitHub Desktop.
Find property by key in nested object
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 findByKey(obj, keyToFind) { | |
| return Object.entries(obj) | |
| .reduce((acc, [key, value]) => (key === keyToFind) | |
| ? acc.concat(value) | |
| : (typeof value === 'object') | |
| ? acc.concat(findByKey(value, keyToFind)) | |
| : acc | |
| , []) | |
| } | |
| // Usage. | |
| findByKey(obj, key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment