-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?

12
  • Have you tried merge instead of extend? Commented Jul 9, 2018 at 15:01
  • $.extend is shallow. the values are simply copied over. Commented Jul 9, 2018 at 15:02
  • What is the desired result? Commented Jul 9, 2018 at 15:04
  • @TA Yeah, I have tried that: var obj = $.merge( $.merge( [], json1 ), json2 ) Commented Jul 9, 2018 at 15:06
  • 1
    Merge them manually. In this case you only have two objects, either with identical keys and one value that differs, just create a new object and merge the arrays. Commented Jul 9, 2018 at 15:21

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

I agree. deep will make the difference.
@DiabolicWords Except... it won't. It doesn't combine values. It won't combine the two arrays into one, it'll simply throw one of them away.
@KevinB is correct - result is the same as w/o deep
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

1 Comment

Interesting option

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.