She*_*zod 8 javascript jquery json
jsfiddle链接:http://jsfiddle.net/vN6fn/1/
假设我有这两个对象:
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"}
] }
Run Code Online (Sandbox Code Playgroud)
最终对象应如下所示:
var final = { data: [
{id:1, comment:"comment1"},
{id:2, comment:"comment2"},
{id:3, comment:"comment3"},
{id:4, comment:"comment4"}
] }
Run Code Online (Sandbox Code Playgroud)
这里有一些要考虑的事情:
$.extend()替换对象,$.merge()不删除重复(我知道我可以做循环,但我正在寻找一个更好的方法来做到这一点).
Roc*_*mat 14
您可以使用$.merge然后浏览并删除重复项,然后对其进行排序.
$.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;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12968 次 |
| 最近记录: |