Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
80
rated 0 times [  84] [ 4]  / answers: 1 / hits: 26825  / 8 Years ago, mon, november 28, 2016, 12:00:00

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?


More From » javascript

 Answers
34

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)




[#59896] Friday, November 25, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shekinah

Total Points: 699
Total Questions: 112
Total Answers: 110

Location: Philippines
Member since Sat, Jul 11, 2020
4 Years ago
;