Skip to content

How to Merge Javascript Objects

A Javascript Object – now just called JSON – is a collection of values and properties stored as a map.

How would you merge two or more Javascript objects together thought?

In ECMAScript 2018, the Object Spread operator will do the trick for you in no time, let’s try it out.

var jso1 = { "name": "John", "colour": "green", }; var jso2 = { "name": "Andrew", "symbol": "arrow", }; var merged = {...jso1, ...jso2};
Code language: JavaScript (javascript)

The result of this would be to combine all the elements and override any newer ones where applicable.

{ name: "Andrew", colour: "green", symbol: "arrow" }
Code language: JavaScript (javascript)

An alternative to using the Spread operator is to use Object.assign as follows:

var merged = Object.assign({}, jso1, jso2);
Code language: JavaScript (javascript)

This results in exactly the same output.

See also  Validate Email Address in Javascript
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x