Skip to content

Instantly share code, notes, and snippets.

@ilearnio
Last active March 23, 2021 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilearnio/08f601f0117c4d9998a2d0d89bf0b44f to your computer and use it in GitHub Desktop.
Save ilearnio/08f601f0117c4d9998a2d0d89bf0b44f to your computer and use it in GitHub Desktop.
Find keys of objects in a deeply nested object or array and return references of that objects
function findKeyDeep(obj, key) {
const foundKeysReferences = [];
if (Array.isArray(obj)) {
obj.forEach(entry =>
foundKeysReferences.push(...findKeyDeep(entry, key)));
} else if (typeof obj === 'object' && obj !== null) {
if (obj[key]) {
foundKeysReferences.push(obj);
}
Object.values(obj).forEach(value =>
foundKeysReferences.push(...findKeyDeep(value, key)));
}
return foundKeysReferences;
};
const obj = [
{a:{b:{c:{d: 3}}}},
{ e:{ d: 4} },
{f:[[{y:{d:6}}]]}
];
findKeyDeep(o, 'd'); // [{"d":3},{"d":4},{"d":6}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment