Last active
April 18, 2021 04:45
-
-
Save Kvit/df8a04e84a2b56b1dda10dd6d42b9b30 to your computer and use it in GitHub Desktop.
Recursive search of complex JSON structures for a given key
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
| const jsonSearch = (obj, searchKey, results = []) => { | |
| const r = results; | |
| // if this is array, iterate elements | |
| if (Array.isArray(obj)) { | |
| //console.log("- ARRAY LENGTH ", obj.length); | |
| for (const element of obj) { | |
| // console.log("-- searching array element: "); | |
| jsonSearch(element, searchKey, r); | |
| } | |
| } else if ( | |
| // if this is object, iterate keys | |
| typeof obj === "object" | |
| ) { | |
| for (let key in obj) { | |
| let value = obj[key]; | |
| // add matching key to results | |
| if (key === searchKey) { | |
| // Optional: unbox array of one | |
| if (Array.isArray(value) && value.length === 1) value = value[0]; | |
| r.push(value); | |
| } | |
| const keyType = typeof obj[key]; | |
| //console.log("key: ", key, " / type: ", keyType); | |
| // look inside objects | |
| if (keyType === "object") { | |
| //console.log("- searching inside object: ", key); | |
| jsonSearch(value, searchKey, r); | |
| } | |
| } | |
| } | |
| return r; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment