本文介绍了如何合并两个JSON对象数组 - 删除重复项并保留Javascript / jQuery中的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
jsfiddle 链接:
假设我有这两个对象:
var obj1 = { data: [
{id:1, comment:"comment1"},
{id:2, comment:"comment2"},
{id:3, comment:"comment3"}
] }
var obj2 = { data: [
{id:2, comment:"comment2"},
{id:3, comment:"comment3"},
{id:4, comment:"comment4"}
] }
最终对象应如下所示:
var final = { data: [
{id:1, comment:"comment1"},
{id:2, comment:"comment2"},
{id:3, comment:"comment3"},
{id:4, comment:"comment4"}
] }
以下是需要考虑的事项:
Here are some things to consider:
- obj1和obj2可能有也可能没有重复
$。 extend()
替换对象, $。合并()
不删除重复项(我知道我可以做循环,但我正在寻找为了更好的方法来做到这一点)。
$.extend()
replaces objects, $.merge()
doesn't remove duplicates (I know I can do for loop, but I'm looking for a better way to do this).
推荐答案
你可以使用 $。合并
然后浏览并删除重复项,然后对其进行排序。
You can use $.merge
and then go through and remove duplicates, and then sort it.
$.merge(obj1.data, obj2.data);
var existingIDs = [];
obj1.data = $.grep(obj1.data, function(v) {
if ($.inArray(v.id, existingIDs) !== -1) {
return false;
}
else {
existingIDs.push(v.id);
return true;
}
});
obj1.data.sort(function(a, b) {
var akey = a.id, bkey = b.id;
if(akey > bkey) return 1;
if(akey < bkey) return -1;
return 0;
});
这篇关于如何合并两个JSON对象数组 - 删除重复项并保留Javascript / jQuery中的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!