0

Possible Duplicate:
Adding two json objects and sorting

Iam having two json objects

[
{"name": "Graduation"},
{"name": "Post Graduation"}
]

and another one is also same

[
{"name": "first sem"},
{"name": "second sem"},
{"name": "third sem"}
]

how can i add two json objects into one,like

[
{"name": "Graduation"},
{"name": "Post Graduation"},
{"name": "first sem"},
{"name": "second sem"},
{"name": "third sem"}
]

I tried

_this.model = new qualification();
_this.model1 = new sems();
 jsondata = _this.model.toJSON();
 jsonData = _.extend(_this.model1.toJSON(),jsonData)

getting json by overriding keys

even I tried
var result = _.union([jsonData1],[jsonData2]);
console.log(JSON.stringify(result));

and with concat also it prints output as

[{"0":{"name":"first sem"},"1":{"name":"second sem"},"2":{"name":"third sem"}},{"0":{"name":"Graduation"},"1":{"name":"Post Graduation"}}],
Cœur
  • 37,241
  • 25
  • 195
  • 267
Venkatesh Bachu
  • 2,348
  • 1
  • 18
  • 28

2 Answers2

1

Well if you are talking of objects then _.extend is perfect but these are arrays. Hence you shall do below

_.union(*array);

Code

var A = [
    {
    "name": "Graduation"},
{
    "name": "Post Graduation"}
];

var B = [
    {
    "name": "first sem"},
{
    "name": "second sem"},
{
    "name": "third sem"}
];

console.log(_.union(A,B)​);​​​​

JsFiddle

http://jsfiddle.net/7FkWs/

Deeptechtons
  • 10,945
  • 27
  • 96
  • 178
0

By "JSON objects" I'm assuming you mean just JavaScript objects, in this case, arrays. You can append them together using the Array#concat() method:

var a1 = [{"name":"Graduation"}, {"name":"Post Graduation"}];
var a2 = [{"name":"first sem"}, {"name":"second sem"}, {"name":"third sem"}];
var a3 = a1.concat(a2);
a3; // [{"name":"Graduation"}, {"name":"Post Graduation"}, {"name":"first sem"}, {"name":"second sem"}, {"name":"third sem"}];

Note that if these objects are indeed serialized JSON strings then you can do the following:

var a4 = JSON.parse(a1).concat(JSON.parse(a2));
a4; // [{"name":"Graduation"}, {"name":"Post Graduation"}, {"name":"first sem"}, {"name":"second sem"}, {"name":"third sem"}];
maerics
  • 151,642
  • 46
  • 269
  • 291