繁体   English   中英

从JSON提取数组元素(javascript)

[英]Extracting array elements from JSON (javascript)

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

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

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

控制台视图:

在此处输入图片说明

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

article()[0] .name

但这是行不通的,我不确定是否有其他解决方法? 感谢您的帮助。 谢谢

您的articles功能将兑现承诺。 你必须消耗的承诺( 更多MDN ):

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

或在async函数中

const articleArray = await articles();
console.log(articleArray);

旁注:您的fetch代码缺少对HTTP成功的检查(HTTP失败不是拒绝)。 到目前为止,您并不是唯一一个错过这张支票的人,以至于我在贫血的博客上写了一篇关于它的文章 带有支票:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM