首页 > 解决方案 > 如何找到 JSON 对象数组的差异?

问题描述

我知道这个问题已经在这里得到了回答,但是每个答案在我的脚本中都不起作用,问这是我最后的手段。

我正在尝试查找上传到数据库的新数据,这是它遵循的逻辑:

从我的 Mongo 数据库存储中读取数据a>> 从 sql server 中提取新数据,存储为b>> 过滤数据并覆盖我的 Mongo 数据库 >> 比较ab查找上传的新文档。

这是我到目前为止的代码:

function comparer(otherArray){
  return function(current){
    return otherArray.filter(function(other){
      return other.value == current.value && other.display == current.display
    }).length == 0;
  }
}

var onlyInA = a.filter(comparer(b));
var onlyInB = b.filter(comparer(a));

result = onlyInA.concat(onlyInB);

console.log(result);

我得到a并且b喜欢这样:

a = await dbo.collection("master").find({ }, {projection:{_id: 0}}).toArray();

//upload all new data here, so b contains more objects than a

b = await dbo.collection("master").find({ }, {projection:{_id: 0}}).toArray();

我希望这会返回所有对象,b除非对象存在于 中a,所以我应该看到新数据。

这是我的数据库的简要示例;

a = [{
            "Process": "Process1",
            "Num": "000000",
        }]

b = [{
            "Process": "Process1",
            "Num": "000000",
        },
        {
            "Process": "Process2",
            "Num": "000107",
        }]

因此b包含更多对象,因此查找差异应显示包含过程2的对象。感谢您的帮助!

标签: javascriptnode.jsmongodb

解决方案


您从中获取的问题/答案comparer引用了名为displayand的属性value,但是您的对象具有属性Processand Num

当您更改为正确的属性时,结果与预期的一样。

var a = [{
            "Process": "Process1",
            "Num": "000000",
        }]

var b = [{
            "Process": "Process1",
            "Num": "000000",
        },
        {
            "Process": "Process2",
            "Num": "000107",
        }]
        
function comparer(otherArray){
  return function(current){
    return otherArray.filter(function(other){
      return other.Process == current.Process && other.Num == current.Num
    }).length == 0;
  }
}

var onlyInA = a.filter(comparer(b));
var onlyInB = b.filter(comparer(a));

result = onlyInA.concat(onlyInB);

console.log(result);


推荐阅读