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

Axios请求处理问题:Map生成数组含大量undefined值

解决GraphQL请求后生成数组出现大量undefined的问题

问题情况

通过Axios发起GraphQL mutation的POST请求后,想要根据返回结果生成目标数组,但最终得到大量undefined值。期望yo返回['112', '113']。

原代码

const func = async (vars, update_vars) => {
  await axiosFunction({ query: create_fields, variables: vars }).then(
    (response) => {
      if (update_vars != undefined) {
        const yo = update_vars.att.map((att) => {
          if (
            att.label === response.data.label
          )
            return response.data.id;
        });
        console.log(yo);
      }
    }
  );
};

数据格式

  • update_vars格式:
[
  { label: 'val 1' },
  { label: 'val 2' },
  { label: 'val 3' },
  { label: 'val 4' }
]
  • response.data格式(实际为包含多个对象的数组):
[
  {
    id: '112',
    other_id: '352009093',
    label: 'val 1'
  },
  {
    id: '113',
    other_id: '3520012',
    label: 'val 2'
  },
  {
    id: '152',
    other_id: '234578',
    label: 'val 13'
  }
]

问题原因

  1. map使用逻辑错误:map会遍历数组所有元素,不满足条件的元素会默认返回undefined,这是出现大量undefined的核心原因。
  2. response.data结构误解:你的response.data是包含多个对象的数组,但原代码直接取response.data.label,无法读取到正确的label值,需要遍历response.data中的每个对象。
  3. update_vars属性调用错误:你给出的update_vars是一个数组,不存在att属性,但原代码用了update_vars.att,导致遍历对象为undefined,进一步引发问题。

修正后的代码

const func = async (vars, update_vars) => {
  const response = await axiosFunction({ query: create_fields, variables: vars });
  if (!update_vars) return;

  // 构建label与id的映射表,提升后续查找效率
  const labelToIdMap = new Map();
  response.data.forEach(item => {
    labelToIdMap.set(item.label, item.id);
  });

  // 遍历update_vars,收集匹配的id并过滤无效值
  const yo = update_vars
    .map(item => labelToIdMap.get(item.label))
    .filter(id => id !== undefined);

  console.log(yo); // 输出 ['112', '113']
};

代码说明

  • 直接用await获取响应结果,避免await与then混用的冗余写法。
  • 先构建映射表labelToIdMap,将返回数据中的label和id对应起来,后续查找更高效。
  • 先用map尝试获取每个label对应的id,再用filter剔除undefined值,最终得到目标数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 17:53:13