Can';t通过JavaScript创建的数组映射';s获取API
我试图通过RESTAPI获取post对象数组,并修改该数组以仅保留我需要的信息 post对象数组来自WordPress REST API,因此输出如下所示 到目前为止,我一直在努力做到以下几点:Can';t通过JavaScript创建的数组映射';s获取API,javascript,arrays,fetch-api,Javascript,Arrays,Fetch Api,我试图通过RESTAPI获取post对象数组,并修改该数组以仅保留我需要的信息 post对象数组来自WordPress REST API,因此输出如下所示 到目前为止,我一直在努力做到以下几点: // 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
// 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
数组
看看这个:我不相信第一个
console.log(articles)
能起作用fetch()
是异步的,您需要将所有代码放入.then()
调用中。我想我已经有了一个数组,因为我将数据推送到了我创建的articles
数组中。当我console.log(文章)时
,我看到一个数组。然后console.log(articles)
必须在.Then()
函数中,不像您在这里显示的那样。@Barmar某些浏览器有一个错误,控制台存储了对对象的实际引用,而不是副本/快照。因此,当您改变对象时,它会“更新”旧日志。可能不是您在日志中看到的文本,但如果您检查本文中提到的某些对象,则肯定是这样。我根本不知道浏览器或这个bug的状态。@Thomas这不是bug,这是预期的行为。当您在控制台中记录一个对象时,它是对该对象的实时引用,因此修改该对象会更改您在那里看到的内容。