How to Merge Javascript Objects

0 min read 126 words

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};

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

{
  name: "Andrew",
  colour: "green",
  symbol: "arrow"
}

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

var merged = Object.assign({}, jso1, jso2);

This results in exactly the same output.

Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags