I'm trying to get an array of post objects via a REST API, and modify that array to only keep the information I need.
The array of post objects comes from the WordPress REST API, so the output looks like this.
Here is what I've tried to do so far:
// 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);
Unfortunately, that doesn't work. filtered
returns an empty array. What's weird is that if instead of using fetch I just paste the contents of the JSON I get from the API directly into a constant, everything works just fine.
What am I missing here? Why can't I modify the array I get from fetch?
Thank you!
Thanks to the suggestions in the comments below, I managed to get this to work. I had to modify the array inside the then()
calls, like so:
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));