hidace hidace - 5 months ago 5
Javascript Question

Iterate over an array and return only matched values?

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;


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.



I suppose this depends if you want to match multiple books or just a single one.

Matching Multiple Books

You can accomplish this via the filter() function, which would handle multiple books :

const favoriteBooks = books.filter((b) => { return b.title == this.props.params.id;});

Matching a Single Book

Otherwise, you likely want the find() function to return a single one :

const favoriteBook = books.find((b) => { return b.title == this.props.params.id;});

Note: Be extremely mindful of how you use the this keyword as it can dramatically change within the context of one of your function calls. You might consider storing it prior to calling the functions or referencing it a different way to avoid unexpected results.