balupton balupton - 3 months ago 9
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
Object.prototype.extend(obj2...)
or
Object.extend(obj1,obj2...)


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

Answer

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Syntax:

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.

Example:

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

Object.assign(obj1, obj2);

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