React中使用JS对数组二次过滤时出现undefined问题求助
First off, let's fix the critical syntax errors in your initial Arr1—these are almost certainly contributing to the undefined issue you're seeing:
- You used commas instead of colons for key-value pairs (e.g.,
"coach", "zeberthal"should be"coach": "zeberthal") - There are malformed quotes around the
quarterbackkey/value (e.g.,""quarterback" "mcman"should be"quarterback": "mcman") - There's an extra closing bracket
]at the end of the array
Here's the corrected, valid version of your arrays:
const Arr1 = [ { "team": "bears", "coach": "zeberthal", "quarterback": "mcman" }, { "team": "vikings", "coach": "jones", "quarterback": "cousins" } ]; const Arr2 = ["vikings", "bears", "packers", "cousins", "mcman"];
Next, let's diagnose why filteredForFirstValue is coming up as undefined:
- Bad array initialization: If React can't parse
Arr1due to syntax errors, any operations on it (likefilter) will fail, leading toundefined. - Incorrect variable assignment: Your original code for
filteredForFirstValuehas invalid arrow function syntax—you're not actually assigning the filtered array to the variable. It should be a direct assignment, not an arrow with extra parentheses:// Wrong syntax that causes undefined // filteredForFirstValue => arr1.filter(function(result){...})) // Correct assignment const filteredForFirstValue = Arr1.filter(result => Arr2.includes(result.team)); - Scope issues: If you're defining
filteredForFirstValueinside a local block (like anifstatement or a callback) in your React component, subsequent code trying to access it won't be able to reach it.
Now, let's address your core requirement: filtering objects where all non-empty fields have values present in Arr2. Instead of filtering step-by-step (which can introduce scope bugs), we can do this in a single, clean filter call that checks all fields at once:
const validTeams = Arr1.filter(teamObj => { // Check every non-empty value in the object exists in Arr2 return Object.values(teamObj).every(value => { // Skip empty strings (since we only care about non-empty fields) if (value === "") return true; return Arr2.includes(value); }); }); console.log(validTeams); // Output: [] (because "zeberthal" and "jones" aren't in Arr2, and those coach fields are non-empty)
If you still prefer step-by-step filtering (maybe for debugging), make sure your code is properly scoped and assigns variables correctly:
// Step 1: Filter teams where team name is in Arr2 const filteredByTeam = Arr1.filter(result => Arr2.includes(result.team)); // Step 2: Filter remaining teams where non-empty coach/quarterback are in Arr2 const filteredFinal = filteredByTeam.filter(result => { const isCoachValid = result.coach === "" || Arr2.includes(result.coach); const isQbValid = result.quarterback === "" || Arr2.includes(result.quarterback); return isCoachValid && isQbValid; }); console.log(filteredFinal); // Still [] for your sample data
In a React component, make sure your arrays are properly initialized (using useState if they're dynamic, or as top-level constants if static) to avoid scope or initialization issues:
import { useState } from 'react'; function TeamFilter() { // Initialize arrays (use useState if they'll change over time) const [arr1] = useState([ { "team": "bears", "coach": "zeberthal", "quarterback": "mcman" }, { "team": "vikings", "coach": "jones", "quarterback": "cousins" } ]); const [arr2] = useState(["vikings", "bears", "packers", "cousins", "mcman"]); const validTeams = arr1.filter(teamObj => { return Object.values(teamObj).every(value => { if (value === "") return true; return arr2.includes(value); }); }); return ( <div> <h2>Valid Teams</h2> {validTeams.length === 0 ? ( <p>No teams meet all criteria</p> ) : ( <ul> {validTeams.map((team, idx) => ( <li key={idx}> {team.team} (Coach: {team.coach}, QB: {team.quarterback}) </li> ))} </ul> )} </div> ); } export default TeamFilter;
内容的提问来源于stack exchange,提问作者questionsneedanswers

