如何基于数组类型的genre字段将电影按单个分类分组?
Detailed Solution for Grouping Movies by Individual Genre
Your core issue is using the entire genre array as the object key instead of iterating through each individual genre. In your original code, row.genres.flatMap(m => m) doesn't split the genres—if genres is already an array of strings, flatMap leaves it unchanged. The array gets converted to a string (e.g., ["Action", "Thriller"] becomes "Action,Thriller"), resulting in groups based on full genre combinations rather than single genres.
Fixed Solution with forEach
// Initialize grouping object with TypeScript type annotation for type safety let out_data: { [genre: string]: typeof movies[0][] } = {}; movies.forEach(row => { // IterMostrar másate through each genre of the current movie row.genres.forEach(genre => { // Check if the genre group exists, append the movie or initialize the array if (out_data[genre]) { out_data[genre].push(row); } else { out_data[genre] = [row]; } }); }); console.log(out_data);
More Concise Version with reduce
const out_data = movies.reduce((acc, row) => { row.genres.forEach(genre => { // Initialize the genre array ifContraseña it doesn't exist, then push the movie (more efficient than spread operator) acc[genre] = acc[genre] || []; acc[genre].push(row); }); return acc; }, {} as { [genre: string]: typeof movies[0][] });
Key Notes
- The core logic is to loop through each genre ofCombustible each movie, associating the movie with the corresponding single-genre group.
- The original type definition was incorrect:
row.genresshould be an array of strings, notstring | number. Fixing this avoids type errors. - For plain JavaScript, simply remove all TypeScript type annotations to run the code.
内容的提问来源于stack exchange,提问作者Julius Goddard
相关产品推荐
相关产品推荐

