Is there a simple way to use the spread ...
operator to combine an array of objects with a another object to create a single object? This example shows what I'm trying to accomplish:
const arrayOfObjects = [ { x: 'foo' }, { y: 'bar' } ]; const obj = { hello: 'world' };
The output I'm looking for is as follows:
{ x: 'foo', y: 'bar', hello: 'world' }
I've tried the following, amongst other things, but it doesn't quite give the intended output.
{ hello: 'world' ...arrayOfObjects } // Gives { 0: { x: 'foo' }, 1: { y: 'bar' }, hello: 'world' };
Is it possible to do this with clever use of the spread operator?
Use the spread syntax (...) to convert an array to an object, e.g. const obj = {... arr} . The spread syntax will unpack the values of the array into a new object, where the indexes of the array are the object's keys and the elements in the array - the object's values. Copied!
The spread syntax takes your array and expands it into elements.
The spread operator unpacks elements of iterable objects such as arrays, sets, and maps into a list. The rest paramter is also denoted by three dots (…). However, it packs the remaining arguments of a function into an array. The spread operator can be used to clone an iterable object or merge iterable objects into one.
Spread syntax (also known as the Spread Operator) is used to copy the enumerable properties of an object to create a clone of it. We can also update an object or merge with another object using the spread syntax.
You can use Object.assign()
with spread syntax ...
const arrayOfObjects = [{ x: 'foo' }, { y: 'bar' }]; const obj = { hello: 'world' }; var result = Object.assign({}, obj, ...arrayOfObjects); console.log(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With