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

JavaScript使用Fetch API获取接口响应后如何筛选指定字段?

代码问题与修正方案

现有代码的问题

  • 混用async/await语法与.then链式调用,逻辑冲突:你在await fetch阶段已经通过.then(res => res.json())将响应解析为JSON数组,此时得到的response变量已经是纯数据,不是Response对象,后续调用response.json()会直接抛出类型错误。
  • 缺少字段提取逻辑,直接返回接口全量数据,没有筛选出你需要的name、numberOfPages、released三个字段。

修正后可运行代码

const fetch = require("cross-fetch");
const URL = "https://anapioficeandfire.com/api/books"

// Important: Don't change the function name
const getBooks = async () => {
  // 发起接口请求获取响应对象
  const response = await fetch(URL);
  // 校验请求是否成功,避免接口异常导致代码崩溃
  if (!response.ok) {
    throw new Error(`请求失败,状态码:${response.status}`);
  }
  // 解析响应为全量JSON数据
  const rawBookList = await response.json();
  // 遍历数据仅保留需要的三个字段
  return rawBookList.map(item => ({
    name: item.name,
    numberOfPages: item.numberOfPages,
    released: item.released
  }));
}

getBooks().then(books => console.log(books))

输出说明

运行代码后返回的数组结构完全匹配你要求的格式,每一项仅包含指定的三个字段。


内容的提问来源于stack exchange,提问作者Faruk Şirket

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:45:03