javascript - 从 JSON 中提取数组元素 (javascript)

标签 javascript arrays json element

我正在尝试操作从 API url 接收到的 JSON 数据(这是我第一次处理此类工作)

以下函数返回一个包含 20 个元素的数组的 promise :

const articles = () => {
return fetch(url)
.then(res => res.json())
.then(post => post.articles);
};

控制台 View :

enter image description here

现在,我想从数组中提取元素 - 我尝试了类似的操作:

articles()[0].name

但这不起作用,我不确定是否有其他方法可以解决此问题?感谢你的帮助。谢谢

最佳答案

您的articles函数返回一个 promise 。您必须消费 promise ( more on MDN ):

articles().then(articleArray => {
    console.log(articleArray);
});

或在async function内:

const articleArray = await articles();
console.log(articleArray);
<小时/>

附注:您的 fetch 代码缺少对 HTTP 成功的检查(HTTP 失败并不是拒绝)。 到目前为止您并不是唯一一个错过这张支票的人,以至于I've written a post on my anemic blog about it 。与支票:

const articles = () => {
    return fetch(url)
    .then(res => {
        if (!res.ok) {
            throw new Error("HTTP error " + res.status);
        }
        return res.json();
    })
    .then(post => post.articles);
};

关于javascript - 从 JSON 中提取数组元素 (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51919200/

相关文章:

javascript - AngularJS - 在方法内丢失 Controller 范围

objective-c - 帮助加载大量数据

arrays - 根据父级更新 int 数组

json - Python & JSON : ValueError: Unterminated string starting at:

c# - 如何在 .NET Core MVC 项目中转换 appsettings.json?

javascript - 变量在 for 循环内的函数内给了我错误的值

javascript - 当使用innerHTML在div上插入文本时,如何阻止div识别HTML标签?

ruby-on-rails - PostgreSQL "could not identify an equality operator for type json"的 Heroku 错误

javascript - Vue 3 - 如何在没有 .value 的情况下使用响应式(Reactive) ref 和计算?

php - 使用 PHP 对数组进行排序以生成多级菜单列表