【发布时间】:2017-12-18 00:02:39
【问题描述】:
我正在尝试通过 REST API 获取帖子对象数组,并修改该数组以仅保留我需要的信息。
帖子对象数组来自 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 得到的数组?
谢谢!
感谢下面 cmets 中的建议,我设法让它工作。我不得不修改 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));
【问题讨论】:
-
我不相信第一个
console.log(articles)有效。fetch()是异步的,你需要把所有代码放在.then()调用中。 -
我想我已经有了一个数组,因为我将数据推送到了我创建的
articles数组中。当我console.log(articles);时,我看到了一个数组。 -
那么
console.log(articles)必须在.then()函数里面,不像你这里展示的那样。 -
@Barmar 某些浏览器存在控制台存储对对象的实际引用而不是副本/快照的错误。因此,当您改变对象时,它会“更新”旧日志。也许不是您在日志中看到的文本,但如果您检查了本文中提到的一些对象,则肯定是这样。 我不知道浏览器或此错误的状态。
-
@Thomas 这不是错误,而是预期的行为。当您在控制台中记录一个对象时,它是对该对象的实时引用,因此修改该对象会改变您在控制台中看到的内容。
标签: javascript arrays fetch-api