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

在React Native中如何提取JSON对象的单个指定字段(如author)

React Native 接口author字段提取修改方案

直接修改现有代码如下即可:

const getArticlesFromApi = async () => {
  try {
    let response = await fetch(
      'http://api.mediastack.com/v1/news'
    )
    // 拿到接口返回的原始新闻数组
    // *注意:如果mediastack接口返回的数组是包裹在data字段下,就改成 (await response.json()).data
    const rawNewsList = await response.json();
    // 遍历数组提取所有author字段,生成纯字符串数组
    const authorList = rawNewsList.map(item => item.author);
    // 如果需要保留对象结构仅保留author字段,可替换为下面的写法
    // const authorList = rawNewsList.map(item => ({ author: item.author }));
    console.log(authorList);
    return authorList;
  } catch (error) {
    console.error('请求失败:', error);
  }
}

说明

  • 核心逻辑使用JS数组的map方法,遍历原新闻对象数组,仅返回我们需要的author字段,最终生成全新的结果数组
  • 额外新增了try/catch错误捕获逻辑,避免接口请求失败、返回格式异常时导致代码崩溃
  • 你的示例数据运行后输出结果为:["OdAdmin", "Graham Gremore"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 06:00:00