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

如何逐步为对象添加属性并构建完整的对象数组?

问题解决:遍历ID并关联对应API结果生成完整数组

你的代码核心问题是**return arr写在了for循环内部**,导致循环只执行一次就直接返回数组,自然只能得到单个对象。

修正方案1:调整return位置(保持原循环逻辑)

把return arr移到循环外部,让循环能完整遍历所有someIds元素,将每个ID对应的对象都添加到数组中:

const arr = []
for (let i = 0; i < someIds.length; i++) {
  const res = await someApiCall() // 返回数组
  arr.push({
    id: someIds[i],
    res
  })
}
// 循环全部执行完再返回数组
return arr

修正方案2:用Promise.all优化异步处理(更优雅高效)

如果API调用之间没有依赖关系,推荐用map结合Promise.all并行处理所有请求,既保证顺序又提升效率:

// 遍历每个ID,生成包含对应结果的Promise
const promiseList = someIds.map(async (id) => {
  const res = await someApiCall()
  return { id, res }
})
// 等待所有请求完成,得到完整结果数组
const arr = await Promise.all(promiseList)
return arr

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 04:55:21