我有两个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"}}],
答案 0 :(得分:1)
如果你在谈论对象,那么_.extend是完美的但是这些是数组。因此,你将在下面做
var A = [
{
"name": "Graduation"},
{
"name": "Post Graduation"}
];
var B = [
{
"name": "first sem"},
{
"name": "second sem"},
{
"name": "third sem"}
];
console.log(_.union(A,B));
答案 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"}];