balupton balupton - 1 year ago 45
Javascript Question

Surely ES6+ must have a way to merge two javascript objects together, what is it?

I'm sick of tired of always having to write code like this:

function shallowExtend(obj1,obj2){
var key;
for ( key in obj2 ) {
if ( obj2.hasOwnProperty(key) === false ) continue;
obj1[key] = obj2[key]

Or if I don't want to write the code myself, implement a library that does it already. Surely ES6+ is coming to the rescue on this will provide us with something like a

So does ES6+ provide such functionality? If not already there, then is such functionality planned? If not planned, then why not?

Answer Source

You will be able to do a shallow merge/extend/assign in ES6 by using Object.assign:


Object.assign(target, ...sources);

where ...sources represents the source object(s).

Note: do not confuse ...sources in the syntax definition with an ES6 spread operator.


var obj1 = {name: 'Daisy', age: 30};
var obj2 = {name: 'Casey'};

Object.assign(obj1, obj2);

console.log( === 'Casey' && obj1.age === 30);
// true