首页 > 解决方案 > 如何比较两个对象数组以找出差异

问题描述

实际上,当我比较两个对象数组时,我遇到了一个迭代问题。

旧数组:

[{uuid:'a'}, {uuid:'b'}, {uuid:'c'}]

阵列新:

[{uuid:'a'}, {uuid:'e'}, {uuid:'f'}]

我要做的是在以下逻辑下调用 api:

  1. 比较 'new' 和 'old' 得到结果:

    [{name:1, uuid:'e'}, {name:1, uuid:'f'}]

然后一一调用POST api添加新的uuid:'e'和'f'

  1. 比较 'new' 和 'old' 得到结果:

    [{name:1, uuid:'b'},{name:1, uuid:'c'}]

然后一一调用Delete api删除uuid: 'b' and 'c'

我试过下面的代码来找出不同之处,但它似乎不正确:(需要一些帮助)

  const postArr = [];
  for (var i = 0; i < this.new.length; i++) {
    for (var o = 0; o < this.old.length; o++) {
      if (
        this.new[i].uuid !==
        this.old[o].uuid
      ) {
        postArr.push(this.new[i]);
      }
    }
  }
  console.log(postArr);

标签: javascript

解决方案


使用过滤器和映射,您可以在旧数组中获得唯一性

var a=[{uuid:'a'}, {uuid:'b'}, {uuid:'c'}];
 var b=[{uuid:'a'}, {uuid:'e'}, {uuid:'f'}];
 var keys = ['uuid'];
 
 console.log(findDifferences(a,b))



function findDifferences(objectA, objectB) {
 
  var result = objectA.filter(function(o1){
    return !objectB.some(function(o2){
        return o1.uuid === o2.uuid;       
    });
  }).map(function(o){

      return keys.reduce(function(newo, name){
          newo[name] = o[name];
          return newo;
      }, {});
  });
  return result;
}


推荐阅读