In an array of objects I need to find a value
-- where key
is activity
: However the activity
key
can be dee
First, your function could be improved by halting once a match is found via the recursive call. Also, you're both declaring match
outside, as well as returning it. Probably better to just return.
const findMatchRecursion = (activity, activityItems) => {
for (let i = 0; i < activityItems.length; i += 1) {
if (activityItems[i].activity === activity) {
return true;
}
if (activityItems[i].items && findMatchRecursion(activity, activityItems[i].items) {
return true;
}
}
return false;
};
There's no built in deep search, but you can use .find
with a named function if you wish.
var result = !!activityItems.find(function fn(item) {
return item.activity === "Gym" || (item.items && item.items.find(fn));
});