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

如何使用JavaScript提取接口返回JSON中指定的users数组并存入对象

问题原因
  • 接口返回的JSON根结构直接包含users数组,不存在你代码中引用的data一级字段,因此mydata.data的值为undefined,调用map方法自然会抛出无法读取undefined属性的错误
  • 此外users本身就是根节点下的数组,不需要在map的回调函数里再访问x.users,数组的每一项直接就是单条user数据
正确实现代码
async function getData(){
  const apiUrl = "https://MyURL"
  const response = await fetch(apiUrl)
  const mydata = await response.json()
  // 直接从返回的根结构取users数组遍历
  const firstnameList = mydata.users.map((x) => x.firstname)
  console.log(firstnameList);
}

getData()
可选健壮性优化

可以增加字段判断和异常捕获逻辑,避免接口返回结构异常、请求失败导致代码报错:

async function getData(){
  try {
    const apiUrl = "https://MyURL"
    const response = await fetch(apiUrl)
    if (!response.ok) throw new Error('接口请求失败')
    const mydata = await response.json()
    // 先判断users是否为数组再执行遍历
    const firstnameList = Array.isArray(mydata?.users) ? mydata.users.map(x => x.firstname) : []
    console.log(firstnameList);
  } catch (err) {
    console.error('执行异常:', err)
  }
}

getData()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 17:33:00