Merge two json/javascript arrays in to one array

Solution 1:

You want the concat method.

var finalObj = json1.concat(json2);

Solution 2:

Upon first appearance, the word "merg" leads one to think you need to use .extend, which is the proper jQuery way to "merge" JSON objects. However, $.extend(true, {}, json1, json2); will cause all values sharing the same key name to be overridden by the latest supplied in the params. As review of your question shows, this is undesired.

What you seek is a simple javascript function known as .concat. Which would work like:

var finalObj = json1.concat(json2);

While this is not a native jQuery function, you could easily add it to the jQuery library for simple future use as follows:

;(function($) {
    if (!$.concat) {
        $.extend({
            concat: function() {
                return Array.prototype.concat.apply([], arguments);
            }
        });
    }
})(jQuery);

And then recall it as desired like:

var finalObj = $.concat(json1, json2);

You can also use it for multiple array objects of this type with a like:

var finalObj = $.concat(json1, json2, json3, json4, json5, ....);

And if you really want it jQuery style and very short and sweet (aka minified)

;(function(a){a.concat||a.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);

;(function($){$.concat||$.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);

$(function() {
    var json1 = [{id:1, name: 'xxx'}],
        json2 = [{id:2, name: 'xyz'}],
        json3 = [{id:3, name: 'xyy'}],
        json4 = [{id:4, name: 'xzy'}],
        json5 = [{id:5, name: 'zxy'}];
    
    console.log(Array(10).join('-')+'(json1, json2, json3)'+Array(10).join('-'));
    console.log($.concat(json1, json2, json3));
    console.log(Array(10).join('-')+'(json1, json2, json3, json4, json5)'+Array(10).join('-'));
    console.log($.concat(json1, json2, json3, json4, json5));
    console.log(Array(10).join('-')+'(json4, json1, json2, json5)'+Array(10).join('-'));
    console.log($.concat(json4, json1, json2, json5));
});
center { padding: 3em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<center>See Console Log</center>

jsFiddle

Solution 3:

You could try merge

var finalObj = $.merge(json1, json2);