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

遍历fetch返回数组仅得单个结果?排查productLines筛选逻辑问题

问题:筛选包含指定productLine的分支数据

我用fetch API获取对象数组,每个对象里嵌套了productLines数组。现在需要筛选出productLines中存在id为11的对象的分支,但当前代码只返回了一个符合条件的结果,实际应该有多个。

我的原代码:

<script>
    fetch('https://swagapi.coburns.com/api/fd/test/GetBranches')
  .then((response) => response.json())
  .then((data) => {
    for(i = 0; i < data.length; i++) {
        if(data[i].productLines[0].id === 11) {
        console.log(data[i])
      }
    }
  })
</script>

问题原因

你只检查了productLines数组的第一个元素的id是否等于11,但很多符合条件的分支里,id=11的productLine可能在数组的其他位置(比如示例数据里就在第6个位置),所以漏掉了大部分结果。

修正方案

需要遍历每个分支的productLines数组,判断其中是否存在id=11的项。推荐用数组的some()方法,它会检查数组中是否有至少一个元素满足条件,代码更简洁高效:

<script>
    fetch('https://swagapi.coburns.com/api/fd/test/GetBranches')
  .then((response) => response.json())
  .then((data) => {
    // 筛选出符合条件的分支
    const filteredBranches = data.filter(branch => {
      // 检查当前分支的productLines中是否存在id为11的项
      return branch.productLines.some(productLine => productLine.id === 11);
    });
    console.log(filteredBranches);
  })
</script>

补充说明

  • filter()方法会遍历整个分支数组,只保留满足条件的分支
  • some()方法会遍历当前分支的productLines数组,只要找到一个id=11的项就返回true,无需遍历全部元素,性能更优
  • 如果需要兼容旧环境,也可以用嵌套for循环替代some(),但some()写法更简洁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 04:36:18