+ 1
Help me understand the lesson (JavaScript)
https://www.sololearn.com/learn/JavaScript/2978/ So, I'm at the part where it talks about spread operators on objects, first it writes we can merge two objects like this: Let obj1 = {.....} Let obj2 = {.....} Let mergedObj = {...obj1, ...obj2} Then it writes trying to merge them like this wouldn't work: Let obj1 = {.....} Let obj2 = {.....} Function merge(...arr){ return {...arr}; } Let mergedObj = merge(obj1, obj2); Which I thought was obvious anyway, and I don't even see why telling us that is even needed. Then it writes we should use Object.assign to merge objects. So should I use spread operator to merge objects or not? Am I the only one who thinks this lesson is very badly made?
1 Answer
+ 4
function merge(...arr) {
return {...arr};
}
Now if you call it,
let mergedObj = merge(obj1, obj2);
The parameter arr becomes [obj1, obj2] #array
{...arr} therefore will be {
0: obj1,
1:obj2,
}
The function merge does not merge objects!
Rewrite the function like this
function(...objects) {
return Object.assign({}, ...objects);
}
Object.assign({}, ...objects) will give
Object.assign({}, obj1, obj2);
Don't be confused though. Spread is still helpful in merging objects like this
var obj3 = {...obj1, ...obj2}