如何从对象数组中提取puppies字段值合并为新数组?
Got it, let's finish that function and also look at some cleaner, more efficient ways to tackle this problem. Here are a few practical approaches:
Completing Your For Loop Implementation
Your existing for loop is on the right track—you just need to fix how you add the puppies to the solution array. Using push() directly with dogs[i].puppies would add the entire array as a single element, so we'll use the spread operator (...) to add each puppy individually:
function collectPuppies(dogs) { let solution = []; for(let i = 0; i < dogs.length; i++){ // Spread the puppies array into individual elements for push() solution.push(...dogs[i].puppies); // Alternative: solution = solution.concat(dogs[i].puppies); } return solution; }
Modern Approach with flatMap
If you're working with ES2019 or later, Array.flatMap() is perfect for this task—it combines mapping each dog to its puppies array and flattening the result in one concise step:
function collectPuppies(dogs) { return dogs.flatMap(dog => dog.puppies); }
Using map + flat (Fallback for Older Environments)
If flatMap isn't available, you can first map each dog to its puppies array, then flatten the resulting array of arrays:
function collectPuppies(dogs) { return dogs.map(dog => dog.puppies).flat(); }
Testing the Function
Let's confirm with your sample data that all approaches work as expected:
const dogs = [ {breed: 'Labrador', puppies: ['Fluffy', 'Doggo', 'Floof'] }, {breed: 'Rottweiler', puppies: ['Biscuits', 'Mary'] } ]; console.log(collectPuppies(dogs)); // Output: ['Fluffy', 'Doggo', 'Floof', 'Biscuits', 'Mary']
内容的提问来源于stack exchange,提问作者VisualXZ

