Reputation: 10957
How can I merge arrays of objects using spread syntax?
My data array
can be any length, I need to combine them all into mergedResults
Any ideas?
Promise.all(apiPromises).then(data => {
let mergedResults = []
data.forEach(function(element) {
const { events } = element;
mergedResults[...events]
console.log(mergedResults)
});
});
Upvotes: 2
Views: 1569
Reputation: 1074355
You can't add to an existing array with spread inside []
, you can only create a new array (like concat
does):
mergedResults = [...mergedResults, ...events];
...which isn't very efficient if modifying the existing array is acceptable (but is common in situations where leaving the original array alone is important, such as when programming with immutable objects).
For that reason, you might use push
with spread syntax instead:
mergedResults.push(...events);
Side note: You can use destructuring in the forEach
parameter list rather than as a separate statement:
Promise.all(apiPromises).then(data => {
let mergedResults = [];
data.forEach(({events}) => {
// -----------^^^^^^^^
mergedResults.push(...events);
});
// ...presumably do something with `mergedResults` here...
});
Perhaps even throw in for-of
:
Promise.all(apiPromises).then(data => {
let mergedResults = [];
for ({events} of data) {
mergedResults.push(...events);
}
// ...presumably do something with `mergedResults` here...
});
Or as with all array operations where you visit all elements, you can shoehorn this into reduce
, but you don't gain anything by it, it just makes things more complicated:
Promise.all(apiPromises).then(data => {
let mergedResults = data.reduce((results, {events}) => {
results.push(...events);
return results;
}, []);
// ...presumably do something with `mergedResults` here...
});
Upvotes: 3
Reputation: 138267
You have to push them:
mergedResults.push(...events);
If you do:
mergedResults[ something ]
thats just a property access.
Upvotes: 3