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

如何将API返回的not_eligible字段匹配ID并入现有数组?

解决方案

要实现将第二个API返回的not_eligible字段匹配id添加到第一个API的对应对象中,你需要修改异步请求的处理逻辑,避免直接push新数据到数组,而是找到对应id的对象并追加字段。以下是两种可行的实现方式:

方式一:遍历并逐个匹配(串行请求)

修改原循环逻辑,使用forEach遍历第一个API的结果,请求对应id的 eligibility 数据后,直接给原对象添加字段:

api.get(`get-participant-reports/${this.userData.ind_id}`)
  .then((res) => {
    this.reportData = res.data;
    // 遍历每个报告项
    this.reportData.forEach(item => {
      api.get(`get-not-eligible360/${item.id}`).then((eligRes) => {
        // 解析第二个API的响应结构(注意响应是嵌套在key为0的对象中)
        const eligibleInfo = eligRes.data[0];
        // 给当前id匹配的对象添加not_eligible字段
        item.not_eligible = eligibleInfo.not_eligible;
        console.log(this.reportData);
      });
    });
  });

方式二:并行请求优化(推荐)

如果数据量较大,使用Promise.all并行处理所有 eligibility 请求,提升性能:

api.get(`get-participant-reports/${this.userData.ind_id}`)
  .then((res) => {
    this.reportData = res.data;
    // 生成所有 eligibility 请求的Promise数组
    const eligibilityRequests = this.reportData.map(item => 
      api.get(`get-not-eligible360/${item.id}`)
    );
    // 等待所有请求完成后统一处理
    Promise.all(eligibilityRequests).then((allResponses) => {
      allResponses.forEach((response, index) => {
        const eligibleInfo = response.data[0];
        this.reportData[index].not_eligible = eligibleInfo.not_eligible;
      });
      console.log(this.reportData);
    });
  });

关键说明

  1. 原代码问题:使用var i会导致异步回调中索引值异常(var是函数级作用域,循环结束后i会固定为数组长度),且直接push响应数据会新增数组元素而非修改原对象。
  2. 响应结构适配:第二个API返回的是{0: {id, not_eligible}}的嵌套结构,因此需要通过res.data[0]取出实际的 eligibility 数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 10:36:24