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' } ]
问题原因
map使用逻辑错误:map会遍历数组所有元素,不满足条件的元素会默认返回undefined,这是出现大量undefined的核心原因。response.data结构误解:你的response.data是包含多个对象的数组,但原代码直接取response.data.label,无法读取到正确的label值,需要遍历response.data中的每个对象。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
相关产品推荐
相关产品推荐

