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

如何获取fetch请求返回的JSON数据中data数组各子元素的第一项

你原来的代码存在两个核心问题:

  • 冗余嵌套了for循环:map方法本身就会遍历整个responseData数组,外层的for逻辑多余,会导致重复执行遍历操作
  • 取值索引错误:map回调中的i是当前遍历元素的下标,el[i]会依次取第一个子数组第0位、第二个子数组第1位,和你要统一取所有子数组第0位的需求不符。

正确实现代码

fetch("api/tesodev.json")
  .then((response) => response.json())
  .then((res) => {
    // 遍历data下的所有子数组,统一取索引0的元素(也就是姓名项)
    const nameList = res.data.map(subArr => subArr[0]);
    // 输出验证
    console.log(nameList);
  });

执行后nameList就是你需要的四个姓名组成的数组:["Hyacinth Vincent", "Brenden Martinez", "Lunea Kinney", "Rhona Mooney"]。

兼容优化(可选)

如果存在子数组为空的极端场景,可以加可选链兜底避免报错:

const nameList = res.data.map(subArr => subArr?.[0] ?? '缺省值');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 05:45:00