使用 jQuery 合并两个包含数组的 JSON 对象

问题描述 投票:0回答:2

我正在尝试合并两个包含数组的 JSON 对象:

var data1 = '{"resourceType": "test", "entry": [{"foo": 123, "test":"foo"},{"foo": 456, "test":"abc"}]}';
var data2 = '{"resourceType": "test", "entry": [{"foo": 789, "test":"bar"},{"foo": 102, "test":"def"}]}';

var json1 = JSON.parse(data1);
var json2 = JSON.parse(data2);

var obj = $.extend({},json1,json2);
console.log(obj);

但是当

data2
将使用这两个对象创建一个数组时,我得到的被
.concat
对象覆盖,而不是我正在寻找的是获取要组合的
entry
对象数组。

JSFiddle

期望的结果应该是这样的:

{"resourceType": "test", 
 "entry": [
    {"foo": 123, "test":"foo"},
    {"foo": 456, "test":"abc"},
    {"foo": 789, "test":"bar"},
    {"foo": 102, "test":"def"}
  ]
}

有什么建议吗?

javascript jquery json merge concatenation
2个回答
1
投票

如果您查看 jquery Extend 的文档,您会发现可以将

deep
作为第一个参数传递:

var obj = $.extend(true, {},json1,json2);

对于您的测试数据,由于对象中的键名称相同,因此结果将只有第二组对象。

如果您想要其他结果,您需要更新您的问题以阐明所需的效果。


更新

如果您希望合并条目,您可以执行以下操作:

var entries = json1.entry.concat(json2.entry);
console.log(entries);

0
投票
Merge two objects x and y deeply, returning a new merged object with the elements from both x and y.

https://www.npmjs.com/package/deepmerge

http://jsfiddle.net/d38L6uhs

© www.soinside.com 2019 - 2024. All rights reserved.