Last active
March 23, 2021 16:21
-
-
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
This file contains 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 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