如何合并两个 JSON 对象数组 - 在 Javascript/jQuery 中删除重复项并保留顺序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9134649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:41:49  来源:igfitidea点击:

How to merge two arrays of JSON objects - removing duplicates and preserving order in Javascript/jQuery?

javascriptjqueryjson

提问by Sherzod

jsfiddlelink: http://jsfiddle.net/vN6fn/1/

jsfiddle链接:http: //jsfiddle.net/vN6fn/1/

Assume I have these 2 objects:

假设我有这两个对象:

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"}
                   ] }

And final object should look like this:

最终对象应如下所示:

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 and obj2 may or may not have duplicates
  • obj1 和 obj2 可能有也可能没有重复

$.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).

$.extend()替换对象,$.merge()不删除重复项(我知道我可以做 for 循环,但我正在寻找更好的方法来做到这一点)。

回答by Rocket Hazmat

You can use $.mergeand then go through and remove duplicates, and then sort it.

您可以使用$.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;
});

回答by sinemetu1

Here is a straight jQuery solution:

这是一个直接的 jQuery 解决方案:

function mergeDeep(o1, o2) {
    var tempNewObj = o1;

    //if o1 is an object - {}
    if (o1.length === undefined && typeof o1 !== "number") {
        $.each(o2, function(key, value) {
            if (o1[key] === undefined) {
                tempNewObj[key] = value;
            } else {
                tempNewObj[key] = mergeDeep(o1[key], o2[key]);
            }
        });
    }

    //else if o1 is an array - []
    else if (o1.length > 0 && typeof o1 !== "string") {
        $.each(o2, function(index) {
            if (JSON.stringify(o1).indexOf(JSON.stringify(o2[index])) === -1) {
                tempNewObj.push(o2[index]);
            }
        });
    }

    //handling other types like string or number
    else {
        //taking value from the second object o2
        //could be modified to keep o1 value with tempNewObj = o1;
        tempNewObj = o2;
    }
    return tempNewObj;
};

Demowith complex objects. I have turned this into a blog-post showing the difference between jQuery's .extend() and my script here.

演示复杂对象。我已经变成了展示jQuery的.extend()和我的脚本之间的差异的博客,留言本在这里

回答by driangle

http://jsfiddle.net/J9EpT/

http://jsfiddle.net/J9EpT/

function merge(one, two){
  if (!one.data) return {data:two.data};
  if (!two.data) return {data:one.data};
  var final = {data:one.data};
  // merge
  for(var i = 0 ; i < two.data.length;i++){
      var item = two.data[i];
      insert(item, final);
  }
  return final;
}


function insert(item, obj){
    var data = obj.data;
    var insertIndex = data.length;
    for(var i = 0; i < data.length; i++){
        if(item.id == data[i].id){
           // ignore duplicates
           insertIndex = -1;
           break;
        } else if(item.id < data[i].id){
           insertIndex = i;
           break;
        }
    }
    if(insertIndex == data.length){
        data.push(item);
    } else if(insertIndex != -1) {
        data.splice(insertIndex,0,item);
    }
}

var final = merge(obj1, obj2);

回答by Vahid Akhtar

Merge two array of objects removing duplicates

合并两个对象数组,删除重复项

  • Using Es6 map()and filter()method
  • 使用 Es6 map()filter()方法

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"}
                    ]}
let obj3 = [...obj1.data, ...obj2.data]

function mergeUniqueArray(arr, comp) {

  let unique = arr
    .map(item => item[comp])

     // store the keys of the unique objects
    .map((item, i, final) => final.indexOf(item) === i && i)

    // eliminate the duplicate keys & store unique objects
    .filter(item => arr[item]).map(item => arr[item]);
    
   return unique;
}

console.log(mergeUniqueArray(obj3,'id'));