I have a JSON object that contains an array of objects. I also have an array of desired values, and I want to search for these values inside my JSON. I only care about the first match. If no match is found, throw an error.
There might be a better way to do this but this is what I came up with:
function myFunction() {
$.getJSON('database.json')
.done(db => {
for (let i = 0; i < desiredValues.length; i++) {
db.arrayOfObjects.forEach(object => {
if (object.propertyValue === desiredValues[i]) {
console.log("Match found!");
return; // break out of myFunction()
}
});
}
throw Error("Match not found.");
})
.fail(error => {
throw Error("getJSON request failed.\n" + error);
})
}
My problem is that the return statement only breaks out of the current iteration of forEach (why?). The remaining objects are still tested for all remaining values of desiredValues, and the error is always thrown. How can I exit myFunction() entirely when a match is found, or how can I restructure this function to achieve what I want?
Edit: I probably should have mentioned I also need to do stuff with the object that was matched, so not just return true if there is a match.