基于show变量筛选指定genre的books对象无结果问题修复
Ah, I see the problem here! Your current filter logic isn’t working because you’re using map() inside the filter callback, which isn’t what filter() expects. Let me break this down and show you how to fix it.
The Problem with the Original Code
The filter() method expects its callback to return a boolean (true or false) to decide whether to keep an element. Right now, you’re returning the result of map(), which is an array. Even if none of the genres match, an array is always a truthy value—so your filter would end up including all books, not just the ones matching the genre. That’s why you’re not getting the expected result.
The Fix
Instead of map(), use the some() method. some() is perfect here because it checks if at least one element in the array meets your condition, and returns a boolean exactly what filter() needs.
Here’s the corrected code:
const booksToShow = show === "All" ? books : books.filter((book) => book.genres.some(g => g.toLocaleLowerCase() === show.toLocaleLowerCase() ) );
Why This Works
some()iterates over each genre in the book’sgenresarray.- For each genre, it converts both the genre and the
showvalue to lowercase (usingtoLocaleLowerCase()for proper case handling across locales) and checks if they match. - As soon as it finds a matching genre, it returns
true, which tellsfilter()to keep that book. If no genres match, it returnsfalse, and the book is excluded.
Testing this with show = "programming" will correctly return both JavaScript for Profissional and CSS for Profissional, since both have "Programming" in their genres.
内容的提问来源于stack exchange,提问作者Saddam Mohsen

