Reputation: 2064
I've been playing with the reduce function a lot lately. I came across this issue, where my function is only returning a single array item from the reduce instead of 2 (there are 2 items in the array)
This is my function:
const pages = await getPosts.reduce((post) => {
const postRoutes = {
[`/blog/${post.slug}`]: {
page: "/blog/post",
query: { 'postSlug': post.slug }
}
};
return postRoutes;
});
Upvotes: 0
Views: 772
Reputation: 3395
reduce
's callback takes two argument: the accumulator and the current value. You need to spread the accumulated data, plus the new data.
It also takes an initial value as its second argument, in this case an empty object.
const example = [{ slug: 'alpha'}, {slug: 'beta'}].reduce((posts, post) => {
const postRoutes = {
[`/blog/${post.slug}`]: {
page: "/blog/post",
query: { 'postSlug': post.slug }
}
};
return {...posts, ...postRoutes };
}, {});
console.log(example);
Upvotes: 2