-1

I'm trying to merge two JSON objects which contains arrays:

var data1 = '{"resourceType": "test", "entry": [{"foo": 123, "test":"foo"},{"foo": 456, "test":"abc"}]}';
var data2 = '{"resourceType": "test", "entry": [{"foo": 789, "test":"bar"},{"foo": 102, "test":"def"}]}';

var json1 = JSON.parse(data1);
var json2 = JSON.parse(data2);

var obj = $.extend({},json1,json2);
console.log(obj);

but what I'm getting is overwritten by data2 object when .concat will create an array with those two objects rather than wham I'm looking for is to get entry array of objects to be combined.

JSFiddle

Desired results should be like:

{"resourceType": "test", 
 "entry": [
    {"foo": 123, "test":"foo"},
    {"foo": 456, "test":"abc"},
    {"foo": 789, "test":"bar"},
    {"foo": 102, "test":"def"}
  ]
}

Any tips on that?

JackTheKnife
  • 3,795
  • 8
  • 57
  • 117

2 Answers2

1

If you look at the documentation of jquery extend you can see that you can pass deep as first argument:

var obj = $.extend(true, {},json1,json2);

With your test data, because the keys in the objects are named the same, the result will just have the second set of objects.

If you want some other result you need to update your question to clarify the desired effect.


Update

If you want the entries to be combined you can do something like this:

var entries = json1.entry.concat(json2.entry);
console.log(entries);
EECOLOR
  • 11,184
  • 3
  • 41
  • 75
0
Merge two objects x and y deeply, returning a new merged object with the elements from both x and y.

https://www.npmjs.com/package/deepmerge

http://jsfiddle.net/d38L6uhs

Arun
  • 41
  • 1
  • 8