So I have two different APIs that I’ve fetched from using await Promise.all()
. They are assigned to a variable called items
. API #1’s response
is an object that would look like this:
{
total: 3,
items: [
{…},
{…},
{…}
]
}
API #2’s response
is just an array of objects.
Now I want to end up with an object looking like the response
from API #1, using a reducer to add the length of API #2’s to the total
and ’merge’ the response
from API #2 into the items
array.
This is what I’ve gone for:
const items = results.reduce((accumulator, { response }) => {
const total = response?.total ?? response?.length
if(!accumulator?.items) {
accumulator.items = []
}
accumulator.items = [
...accumulator.items,
...(response?.items ?? response)
]
return ({
...accumulator,
total: (accumulator?.total ?? 0) + total
})
}, {})
I’m quite a noob when it comes to reduce()
and my gut feeling is that there could definitely be a cleaner/more structured way of accomplishing the same result. Any major hiccups that I should re/-consider?
Thanks!