添加两个json对象

时间:2012-05-16 16:11:06

标签: javascript json backbone.js

  

可能重复:
  Adding two json objects and sorting

我有两个json对象

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

另一个也是一样

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

如何将两个json对象添加到一个,如

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

我试过

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

通过覆盖键来获取json

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

并且使用concat也将输出打印为

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

2 个答案:

答案 0 :(得分:1)

如果你在谈论对象,那么_.extend是完美的但是这些是数组。因此,你将在下面做

_.union(*array);

代码

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/

答案 1 :(得分:0)

通过“JSON对象”我假设你只是指JavaScript对象,在本例中是数组。您可以使用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"}];

请注意,如果这些对象确实是序列化的JSON字符串,那么您可以执行以下操作:

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