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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

JSON data is actually string. It only becomes array when converted
@charlietfl Yup, the OP can use JSON.parse() to convert it. Better right?\
it's just the definition thing... so many people getting confused these days when they see arrays or objects and calling them JSON and vice versa
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.

Comments

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.