Javascript — How to merge 2 JSON strings together and return a string

Marika Lam
2 min readJun 14, 2022

Purpose

We will assume that we are starting from two JSON strings and, at the end, we want to obtain a single JSON string with the merged objects.

How to merge 2 JSON objects together

  1. We will start our code by defining two JSON strings containing two different objects. These are the objects we will merge.
const string1  = `{"name": "Todd","age": 20}`;const string2 = `{"languages": ["Spanish", "Portuguese"],"married": true}`;

2. After defining these JSON strings, we will parse them to JavaScript objects.

const obj1 = JSON.parse(string1);const obj2 = JSON.parse(string2);

3. We will start by defining a new object with brackets. Then, we will use the spread operator “” to copy the properties of each original object to the new one.

const mergedObject = {...obj1,...obj2};

Note:

Here in this example, we are doing a shallow copy, so you should be careful to not end up mutating the properties of the original objects, in case they are references to nested…

--

--