-5

I have two JSON Objects like this:

First one:

[{
    "id": 5001,
    "count": "0",
    "type": "None"
},
{
    "id": 5002,
    "count": "0",
    "type": "Glazed"
},
{
    "id": 5005,
    "count": "0",
    "type": "Sugar"
},
{
    "id": 5003,
    "count": "0",
    "type": "Chocolate"
},
{
    "id": 5004,
    "count": "0",
    "type": "Maple"
},
{
    "id": 5009,
    "count": "0",
    "type": "Juice"
}]

Second one:

[{
    "id": 5001,
    "count": "1"
},
{
    "id": 5002,
    "count": "10"
},
{
    "id": 5005,
    "count": "20"
},
{
    "id": 5003,
    "count": "70"
},
{
    "id": 5004,
    "count": "50"
},
{
    "id": 5009,
    "count": "0"
}]

How can I combine these two JSON Objects like:

[{
    "id": 5001,
    "count": "1",
    "type": "None"
},
{
    "id": 5002,
    "count": "10",
    "type": "Glazed"
},
{
    "id": 5005,
    "count": "20",
    "type": "Sugar"
},
{
    "id": 5003,
    "count": "70",
    "type": "Chocolate"
},
{
    "id": 5004,
    "count": "50",
    "type": "Maple"
},
{
    "id": 5009,
    "count": "0",
    "type": "Juice"
}]

Please help me, Thanks in advance.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
selvam
  • 1,177
  • 4
  • 18
  • 40

2 Answers2

1

Since JSON data is an array, you can use the standard array function .push():

data.push(data1);

Fiddle:

var data = [{"id": 1, "name": "Praveen"}, {"id": 2, "name": "Kumar"}];
var newD = [{"id": 3, "name": "StackOverflow"}];
data.push(newD[0]);

You can check out the contents of data, by using a console.log(data).


Or you can also use extend:

var object = $.extend({}, object1, object2);

by passing an empty object as the target(first) argument you can preserve both the objects if however you want to merge the second object you can do it like

$.extend(object1, object2);

Fiddle: http://jsfiddle.net/praveenscience/gyysg5zm/

Reference: Merge two json objects with jquery.

Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

You can try this:

function merge_options(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}

from: How can I merge properties of two JavaScript objects dynamically?

and customize for your needs, for example to overwrite lower count.

Community
  • 1
  • 1
mdargacz
  • 1,267
  • 18
  • 32