gpt4 book ai didi

javascript - 如何找到 JSON 对象数组的差异?

转载 作者:可可西里 更新时间:2023-11-01 10:08:21 26 4
gpt4 key购买 nike

我知道这个问题已经得到回答here ,但是每一个答案在我的脚本中都不起作用,问这是我最后的选择。

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

从我的 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);

我像这样获得ab:

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 中获取的问题/答案引用了名为 displayvalue 的属性,但是您的对象具有属性 ProcessNum

当您更改为正确的属性时,结果符合预期。

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);

关于javascript - 如何找到 JSON 对象数组的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56774158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com