You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从对象数组中提取puppies字段值合并为新数组?

Solution to Collect All Puppies into a Single Array

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:49:37