Last active
October 2, 2025 11:43
-
-
Save leandroandrade/9728c2e8a59604ccd5e07daf1a9af7f2 to your computer and use it in GitHub Desktop.
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 getValueByKeyJson(obj, key) { | |
| if (obj === null || typeof obj !== 'object') { | |
| return undefined; | |
| } | |
| if (obj.hasOwnProperty(key)) { | |
| return obj[key]; | |
| } | |
| for (const property in obj) { | |
| if (obj.hasOwnProperty(property)) { | |
| const found = getValueByKeyJson(obj[property], key); | |
| if (found !== undefined) { | |
| return found; | |
| } | |
| } | |
| } | |
| return undefined; | |
| } | |
| // more robust | |
| function getValueByKey(obj, key, returnAll = false) { | |
| const results = []; | |
| this._searchRecursive(obj, key, results); | |
| if (results.length === 0) { | |
| return returnAll ? [] : undefined; | |
| } | |
| return returnAll ? results : results[0]; | |
| } | |
| function _searchRecursive(obj, key, results) { | |
| if (obj === null || typeof obj !== 'object') { | |
| return; | |
| } | |
| if (Object.prototype.hasOwnProperty.call(obj, key)) { | |
| results.push(obj[key]); | |
| } | |
| for (const property in obj) { | |
| if (Object.prototype.hasOwnProperty.call(obj, property)) { | |
| this._searchRecursive(obj[property], key, results); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment