javascript - 如何找到 JSON 对象数组的差异?
问题描述
我知道这个问题已经在这里得到了回答,但是每个答案在我的脚本中都不起作用,问这是我最后的手段。
我正在尝试查找上传到数据库的新数据,这是它遵循的逻辑:
从我的 Mongo 数据库存储中读取数据a
>> 从 sql server 中提取新数据,存储为b
>> 过滤数据并覆盖我的 Mongo 数据库 >> 比较a
并b
查找上传的新文档。
这是我到目前为止的代码:
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的对象。感谢您的帮助!
解决方案
您从中获取的问题/答案comparer
引用了名为display
and的属性value
,但是您的对象具有属性Process
and 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);
推荐阅读
- wso2 - 开发者门户 API 返回 401
- r - 确定输入是否是 R 中的结构体数组字段
- javascript - 函数返回类型的打字稿类型转换
- c# - 即使不调用 Complete 方法,TransactionScope 也会保存数据
- c# - 如何将所需的 Json List 对象以及剩余的 Json 属性提取到模型类中?
- c++ - 包含其他带有浮点数的向量和另一个整数向量的向量
- c++ - 是否可以在 C++ 中的类的静态方法中初始化静态成员?
- java - Java - Criteria API - Unidirectional OneToMany
- python - python for loop result in ffmpeg command
- openshift-client-tools - Openshift: list unused secrets