在React Native中如何提取JSON对象的单个指定字段(如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
相关产品推荐
相关产品推荐

