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

将循环中多次API调用结果合并为数组并移除空数组

解决方案:合并多API调用的数组结果并过滤空数组

Hey there, let's work through this problem together! From what you described, you're making multiple API calls based on zip code and radius, getting back a mix of empty arrays and arrays with data (1-20 items max), and you need to combine all those into a single clean array without the empty ones. Here's how to do it in a couple of common languages:

JavaScript Implementation

First, let's assume you've collected all your API responses into an array (even the empty ones). The simplest way to handle this is with the flat() method—it automatically flattens one level of arrays and ignores empty ones entirely:

// Example collected API responses
const apiResponses = [
  [], // Empty array to discard
  [{ id: 1, name: "Downtown Shop" }],
  [{ id: 2, name: "Suburban Mall" }, { id: 3, name: "Neighbor Store" }],
  [], // Another empty array
  [{ id: 4, name: "Industrial Warehouse" }]
];

// Merge and remove empty arrays in one line
const mergedResults = apiResponses.flat();

// If you prefer a more explicit step-by-step approach:
// 1. Filter out empty arrays first
const nonEmptyResponses = apiResponses.filter(res => res.length > 0);
// 2. Merge the remaining arrays
const mergedResults = nonEmptyResponses.reduce((combined, current) => combined.concat(current), []);

console.log(mergedResults);
// Output: [{ id:1, ... }, { id:2, ... }, { id:3, ... }, { id:4, ... }]

If your API calls are asynchronous (which they almost always are), use Promise.all() to wait for all calls to finish before processing:

// Assume getLocations is your API call function
const fetchAllLocations = async (zipCode, radius) => {
  // Let's say you need to make 3 different radius calls as an example
  const apiCalls = [
    getLocations(zipCode, radius),
    getLocations(zipCode, radius + 5),
    getLocations(zipCode, radius + 10)
  ];

  try {
    const apiResponses = await Promise.all(apiCalls);
    return apiResponses.flat();
  } catch (err) {
    console.error("Failed to fetch locations:", err);
    throw err;
  }
};

// Usage
fetchAllLocations("90210", 10)
  .then(mergedResults => console.log("Final merged data:", mergedResults));

Python Implementation

For Python, a list comprehension is the most concise way to handle this. It iterates over each sub-array and collects all their elements—empty arrays just don't contribute any elements:

# Example collected API responses
api_responses = [
    [],
    [{"id": 1, "name": "Downtown Shop"}],
    [{"id": 2, "name": "Suburban Mall"}, {"id": 3, "name": "Neighbor Store"}],
    [],
    [{"id": 4, "name": "Industrial Warehouse"}]
]

# Merge and remove empty arrays
merged_results = [item for sublist in api_responses for item in sublist]

print(merged_results)
# Output: [{'id': 1, ...}, {'id': 2, ...}, {'id': 3, ...}, {'id': 4, ...}]

For async Python with asyncio, you'd use asyncio.gather() to wait for all API calls, then process the same way:

import asyncio

# Assume get_locations is your async API function
async def fetch_all_locations(zip_code, radius):
    api_calls = [
        get_locations(zip_code, radius),
        get_locations(zip_code, radius + 5),
        get_locations(zip_code, radius + 10)
    ]
    api_responses = await asyncio.gather(*api_calls)
    return [item for sublist in api_responses for item in sublist]

# Run the async function
asyncio.run(fetch_all_locations("90210", 10))

Key Notes

  • Make sure you're collecting every API response (even empty ones) into a single array/list before processing.
  • The methods above work regardless of how many empty arrays you have—they'll all get stripped out automatically.
  • If you're working with a different language, the core logic stays the same: filter out empty collections, then flatten/merge the rest into one.

内容的提问来源于stack exchange,提问作者Chuck LaPress

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:07:09