[javascript] Merge two json/javascript arrays in to one array

I have two json arrays like

var json1 = [{id:1, name: 'xxx' ...}]
var json2 = [{id:2, name: 'xyz' ...}]

I want them merge in to single arrays

var finalObj = [{id:1, name: 'xxx' ...},{id:2, name: 'xyz' ...}]

This question is related to javascript jquery json

The answer is


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);

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

jsFiddle


You can achieve this using Lodash _.merge function.

_x000D_
_x000D_
var json1 = [{id:1, name: 'xxx'}];_x000D_
var json2 = [{id:2, name: 'xyz'}];_x000D_
var merged = _.merge(_.keyBy(json1, 'id'), _.keyBy(json2, 'id'));_x000D_
var finalObj = _.values(merged);_x000D_
_x000D_
console.log(finalObj);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_


You can use the new js spread operator if using es6:

_x000D_
_x000D_
var json1 = [{id:1, name: 'xxx'}]_x000D_
var json2 = [{id:2, name: 'xyz'}]_x000D_
var finalObj = [...json1, ...json2]_x000D_
_x000D_
console.log(finalObj)
_x000D_
_x000D_
_x000D_


Maybe, you can use the array syntax of javascript :

var finalObj =[json1 , json2]

You can do this using Es 6 new feature :

var json1 = [{id:1, name: 'xxx' , ocupation : 'Doctor' }];

var json2 = [{id:2, name: 'xyz' ,ocupation : 'SE'}];

var combineJsonArray = [...json1 , ...json2];

//output should like this [ { id: 1, name: 'xxx', ocupation: 'Doctor' },
  { id: 2, name: 'xyz', ocupation: 'SE' } ]

Or You can put extra string or anything between two json array :

var json3 = [...json1 ,"test", ...json2];

// output should like this : [ { id: 1, name: 'xxx', ocupation: 'Doctor' },
  'test',
  { id: 2, name: 'xyz', ocupation: 'SE' } ]

Try the code below, using jQuery extend method:

var json1 = {"name":"ramesh","age":"12"};

var json2 = {"member":"true"};

document.write(JSON.stringify($.extend(true,{},json1,json2)))

var json1=["Chennai","Bangalore"];
var json2=["TamilNadu","Karanataka"];

finaljson=json1.concat(json2);

Since you are using jQuery. How about the jQuery.extend() method?

http://api.jquery.com/jQuery.extend/

Description: Merge the contents of two or more objects together into the first object.


You could try merge

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?