gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:46:21 25 4
gpt4 key购买 nike

我正在尝试操作从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com