gpt4 book ai didi

javascript - 无法映射通过 JavaScript 的 fetch API 创建的数组

转载 作者:太空宇宙 更新时间:2023-11-04 15:27:54 25 4
gpt4 key购买 nike

我正在尝试通过 REST API 获取 post 对象数组,并修改该数组以仅保留我需要的信息。

post 对象数组来自 WordPress REST API,因此输出看起来像 this .

这是我迄今为止尝试做的事情:

// We'll be pulling data from this URL.
const endpoint = 'https://wordpress.org/news/wp-json/wp/v2/posts';

// Let's create an array where we will store this data.
const articles = [];

// Let's fetch the data with JavaScript's Fetch API.
fetch(endpoint)
.then(blob => blob.json())
.then(data => articles.push(...data));

// If we console log at this point, we have all the posts.
console.log(articles);

// Now let's loop through the data and create a new constant with only the info we need.
const filtered = articles.map(post => {
return {
id: post.id,
title: post.title.rendered,
link: post.link,
date: post.date,
excerpt: post.excerpt.rendered,
};
});

// filtered should now be an array of objects with the format described above.
console.log(filtered);

不幸的是,这不起作用。 filtered返回一个空数组。奇怪的是,如果我不使用 fetch,而是将从 API 获取的 JSON 内容直接粘贴到常量中,那么一切都会正常工作。

我在这里缺少什么?为什么我无法修改从 fetch 获取的数组?

谢谢!

<小时/>

感谢下面评论中的建议,我设法让它发挥作用。我必须修改 then() 内的数组调用,如下所示:

fetch(endpoint)
.then(blob => blob.json())
.then(function(data) {
return data.map(post => {
return {
id: post.id,
title: post.title.rendered,
link: post.link,
date: post.date,
excerpt: post.excerpt.rendered,
};
});
})
.then(data => articles.push(...data));

最佳答案

fetch(endpoint) 是一个异步函数。您正尝试在 fetch 响应之前映射 articles 数组。

看看这个:Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

关于javascript - 无法映射通过 JavaScript 的 fetch API 创建的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45076657/

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