2

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)
                });
   });
1
  • You're trying to merge together every object in the array in to one resulting object? Can you give an example input and desired output maybe? Commented Aug 10, 2018 at 12:35

2 Answers 2

3

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...
});
Sign up to request clarification or add additional context in comments.

Comments

3

You have to push them:

  mergedResults.push(...events);

If you do:

  mergedResults[ something ]

thats just a property access.

2 Comments

So that's what the W stands for. :-)
@crowder yeah when I joined SO I still cared somewhat about my privacy, but I gave up now ... :) (you still have to google a lot to find anything meaningful about me so ...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.