I'm working with JSON and would like to iterate over an array and just return the value I'm looking for. For example, if I have an array of objects and each of those objects has information for a particular book, how can I iterate over each object in that array and only return the one that matches?
I've tried using map, like so (but doesn't work the way I need it to):
// books is from my imported JSON object
const favoriteBook = books.map((book) => {
if (book.title == this.props.params.id) {
return book;
}
});
console.log(favoriteBook)
However, when I console.log(favoriteBook), I'm seeing an array with one object returned that matches, plus 'undefined' for all the ones that don't match. How can I have it stop as soon as it finds the match and just return that one? Wondering how to do this with 'filter' if possible (?) or a similar way.
Thanks.