Created
March 19, 2019 10:18
-
-
Save dacre-denny/2753e0786c1da1d41d119697aa4c2001 to your computer and use it in GitHub Desktop.
Find nested object recursively
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 myObject = [{ | |
"myItems": [{ | |
"id": 1, | |
"group": { | |
"groupId": 33 | |
}, | |
}, | |
{ | |
"id": 2, | |
"group": { | |
"groupId": 44 | |
} | |
} | |
] | |
}]; | |
const find = (object, predicate) => { | |
/* Catch any exceptions thrown when evaluating predicate */ | |
const safePredicate = () => { | |
try { | |
return predicate(object); | |
} | |
catch(err) { | |
return false; | |
} | |
}; | |
/* If object satisifies predicate then return it */ | |
if(safePredicate(object)) { | |
return object; | |
} | |
/* Otherwise search for match in object's value fields */ | |
else { | |
for(const [_,value] of Object.entries(object)) { | |
/* If value field is an array, search each value | |
of array */ | |
if(Array.isArray(value)) { | |
for(const item of value) { | |
const result = find(item, predicate); | |
if(result) { | |
return result; | |
} | |
} | |
} | |
/* If value is object, search that object recursivly */ | |
else if(typeof value === "object") { | |
const result = find(value, predicate); | |
if(result) { | |
return result; | |
} | |
} | |
} | |
} | |
}; | |
/* Find object with matching shape and desired groupId value */ | |
const result = find(myObject, object => object.group.groupId === 44); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment