0

可能重复:
添加两个 json 对象并排序

我有两个 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"}}],
4

2 回答 2

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

提琴手

http://jsfiddle.net/7FkWs/

于 2012-05-16T16:19:52.927 回答
0

通过“JSON 对象”,我假设您只是指 JavaScript 对象,在这种情况下是数组。Array#concat()您可以使用以下方法将它们附加在一起:

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"}];
于 2012-05-16T16:19:36.937 回答