如何使用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
相关产品推荐
相关产品推荐

