Skip to content

Instantly share code, notes, and snippets.

@leandroandrade
Last active October 2, 2025 11:43
Show Gist options
  • Select an option

  • Save leandroandrade/9728c2e8a59604ccd5e07daf1a9af7f2 to your computer and use it in GitHub Desktop.

Select an option

Save leandroandrade/9728c2e8a59604ccd5e07daf1a9af7f2 to your computer and use it in GitHub Desktop.
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