Merging Javascript Objects with the Spread Operator

javascript
Published on August 22, 2019

Use-Cases of this Tutorial

  • Merge multiple Javascript objects.

The Spread operator denoted by three dots ... expands an iterable (e.g. array). Earlier it was not possible to use the Spread operator on a normal object, but a recent proposal has made it possible to use the Spread operator to copy its properties into another object.

To know the basics of the Spread operator you can refer Javascript Spread Operator.

Just like the Spread operator provides a shorter syntax to merge arrays, it can also be used to merge objects. However only enumerable properties of the object can be copied. Enumerable properties of an object are those properties and methods that have its enumerable flag set to true. Non-enumerable properties are basically "uncountable".

However for simple cases you don't have to worry about enumerability.

Example - Merging Objects Containing Only Properties

var ob = { first: "Lewis", second: "Valtteri" };
var ob2 = { third: "Max", fourth: "Sebastian" };
var ob3 = { fourth: "Demo", fifth: "Charles" };

// merging the above objects
var top_five = { ...ob, ...ob2, ...ob3 };

// { first: "Lewis", second: "Valtteri", third: "Max", fourth: "Demo", fifth: "Charles" }
console.log(top_five);

Note that if input objects have the same property / method name, the created object will get the property / method value from the last occurring object.

Example - Merging Objects Containing Methods

var ob = { x: 12, y: 18, z: 34 };
var ob2 = {
		a: 10,
		display: function() {
			console.log("Hello World");
		}
	};

var merged_ob = { ...ob, ...ob2 };

// "Hello World"
merged_ob.display();
In this Tutorial