114

I have two JSON objects with the same structure and I want to concat them together using Javascript. Is there an easy way to do this?

3
  • How exactly do you want to concat them? Each element of both objects or both objects as a new object having the origin objects as elements or …? Commented Jan 11, 2009 at 20:33
  • 2
    Basically I have an array of 10 Json objects. I then make an Ajax call to get another 10 Json objects and I want to concat them together to create an array of 20 objects. Commented Jan 11, 2009 at 21:04
  • Do you have JSON objects (deserialized into a variable of type Object) or strings (serialized form)? Commented Jan 14, 2009 at 16:47

15 Answers 15

121

Based on your description in the comments, you'd simply do an array concat():

var jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}];
var jsonArray2 = [{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];

jsonArray1 = jsonArray1.concat(jsonArray2);

console.log(jsonArray1)
// [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}, {'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];

Sign up to request clarification or add additional context in comments.

3 Comments

Your assumption about the value of jsonArray1 is incorrect. concat doesn't modify the original array, it returns a new array.
You'd need to do jsonArray1 = jsonArray1.concat(jsonArray2);
For the 1, 2, 3 this can be handy for a clean merge: var arr3 = [].concat(arr1, arr2);
55

The actual way is using JS Object.assign.

Object.assign(target, ...sources)

MDN Link

There is another object spread operator which is proposed for ES7 and can be used with Babel plugins.

 Obj = {...sourceObj1, ...sourceObj2}

Comments

47

If you'd rather copy the properties:

var json1 = { value1: '1', value2: '2' };
var json2 = { value2: '4', value3: '3' };


function jsonConcat(o1, o2) {
 for (var key in o2) {
  o1[key] = o2[key];
 }
 return o1;
}

var output = {};
output = jsonConcat(output, json1);
output = jsonConcat(output, json2);

Output of above code is{ value1: '1', value2: '4', value3: '3' }

2 Comments

As they are objects, you don't need to return it, as objects are passed by reference
Had an interesting corner case where I needed to merge properties from two JSON objects, this worked like a charm. Thanks.
41

I use:

let x = { a: 1, b: 2, c: 3 }

let y = {c: 4, d: 5, e: 6 }

let z = Object.assign(x, y)

console.log(z)

// OUTPUTS:
{ a:1, b:2, c:4, d:5, e:6 }

From here.

Comments

27

You can use jquery extend method.

Example:

o1 = {"foo":"bar", "data":{"id":"1"}};
o2 = {"x":"y"};
sum = $.extend(o1, o2);

Result:

sum = {"foo":"bar", "data":{"id":"1"}, "x":"y"}

3 Comments

Better solution
Simpler and cleaner solution.
A case where jQuery isn't overkill.
21

if using TypeScript, you can use the spread operator (...)

var json = {...json1,...json2} 

1 Comment

Thank you!, for some reason, this have worked better on react, to use with render states
18

One solution is to use a list/array:

var first_json = {"name":"joe", "age":27};
var second_json = {"name":"james", "age":32};

var jsons = new Array();
jsons.push(first_json);
jsons.push(second_json);

Result

jsons = [
    {"name":"joe", "age":27},
    {"name":"james", "age":32}
]

2 Comments

Cough, what about [first_json, second_json]?
That's certainly correct if the OP has has only two objects, but since they specifically mentioned concatenation, it seemed more likely this was a contrived example looking for a way to append.
12

You can use Object.assign() method. The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.[1]

var o1 = { a: 1 }, o2 = { b: 2 }, o3 = { c: 3 };

var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }

2 Comments

Best, concise code with a relevant example so far! It would be nice if you clarify what happens when the keys are not unique across different objects :)
if o1, o2, contains the same keys, the right one is assigned to the obj. JSON.stringify(Object.assign({ "test": 1 }, { "test": 2 }, { "test": 3 }, { "test2": 4 } )); => '{"test":3,"test2":4}'
6

okay, you can do this in one line of code. you'll need json2.js for this (you probably already have.). the two json objects here are unparsed strings.

json1 = '[{"foo":"bar"},{"bar":"foo"},{"name":"craig"}]';

json2 = '[{"foo":"baz"},{"bar":"fob"},{"name":"george"}]';

concattedjson = JSON.stringify(JSON.parse(json1).concat(JSON.parse(json2)));

Comments

2

Just try this, using underscore

var json1 = [{ value1: '1', value2: '2' },{ value1: '3', value2: '4' }];
var json2 = [{ value3: 'a', value4: 'b' },{ value3: 'c', value4: 'd' }];
var resultArray = [];
json1.forEach(function(obj, index){
  resultArray.push(_.extend(obj,  json2[index]));
});

console.log("Result Array", resultArray);

Result

Comments

1
var baseArrayOfJsonObjects = [{},{}];
for (var i=0; i<arrayOfJsonObjectsFromAjax.length; i++) {
    baseArrayOfJsonObjects.push(arrayOfJsonObjectsFromAjax[i]);
}

Comments

1

I use:

let jsonFile = {};    
let schemaJson = {};    
schemaJson["properties"] = {};    
schemaJson["properties"]["key"] = "value";
jsonFile.concat(schemaJson);

Comments

1

The simplest way :

const json1 = { value1: '1', value2: '2' };
const json2 = { value2: '4', value3: '3' };

const combinedData = {
  json1,
  json2
};

console.log(combinedData)

Comments

1

I dont know if you want this:

U can use this for create from arrays, all arrays need contains the same number of elments.

Example: If you have:

let a = ["a", "b", "c"];
let b = [1, 2, 3];

Use

concatArraysLikeJson([a, b]);

The result of is:

let result = {
 0 : ["a", 1],
 1 : ["b", 2],
 2 : ["c", 3]
};

Typescript

concatArraysLikeJson(arrays:any){
 let result:any = {};

 let size:number = 0;
 let make:boolean = true;

 if(arrays.length > 0){
  size = arrays[0].length;

  for(let i = 1; i < arrays.length; i++){
    let array = arrays[i];
    
    if(make){
      if(array.length != size){
        make = false;
      }
    }
  }
 }

 if(make){
  for (let o = 0; o < size; o++) {
    result[o] = [];
  }

  for(let i = 0; i < arrays.length; i++){
    const array = arrays[i];

    //console.log(array);

    for (let o = 0; o < size; o++) {
      const element = array[o];
      result[o].push(element);
    }
  }

  return result;
 }else{
  return false;
 }
}

Javascript:

concatArraysLikeJson(arrays){
 let result = {};

 let size = 0;
 let make = true;

 if(arrays.length > 0){
  size = arrays[0].length;

  for(let i = 1; i < arrays.length; i++){
    let array = arrays[i];
    
    if(make){
      if(array.length != size){
        make = false;
      }
    }
  }
}

if(make){
  for (let o = 0; o < size; o++) {
    result[o] = [];
  }

  for(let i = 0; i < arrays.length; i++){
    const array = arrays[i];

    //console.log(array);

    for (let o = 0; o < size; o++) {
      const element = array[o];
      result[o].push(element);
    }
  }

  return result;
}else{
  return false;
}
  }

Comments

-1

The JSON Objects and Arrays can be combined in multiple ways within a structure

I can merge json with rules using json-object-merge

import JSONObjectMerge from "json-object-merge";

const target = {
  store: {
    book: [
      {
        category: "reference",
        author: "Nigel Rees",
        title: "Sayings of the Century",
        price: 8.95
      }
    ],
    bicycle: {
      color: "red",
      price: 19.95
    }
  }
};

const source = {
  store: {
    book: [
      {
        category: "fiction",
        author: "Evelyn Waugh",
        title: "Sword of Honour",
        isbn: "0-679-43136-5",
        price: 12.99
      }
    ]
  }
};
const merged = JSONObjectMerge(target, source, { "$.store.book": "PREPEND" });

expect(merged).toEqual({
  store: {
    book: [
      {
        // books from source are prepended to the original array
        category: "fiction",
        author: "Evelyn Waugh",
        title: "Sword of Honour",
        isbn: "0-679-43136-5",
        price: 12.99
      },
      {
        category: "reference",
        author: "Nigel Rees",
        title: "Sayings of the Century",
        price: 8.95
      }
    ],
    bicycle: {
      color: "red",
      price: 19.95
    }
  }
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.