gpt4 book ai didi

javascript - 如何在 react 中找到两个嵌套数组之间的不匹配元素

转载 作者:行者123 更新时间:2023-12-04 09:11:15 25 4
gpt4 key购买 nike

我在下面有两个数组。
数组 1:

{
"0":{
"countries":{
"BDI":{
"count":1
},
"IRN":{
"count":1
}
},
"checkId":"16835659691517226105"
},
"1":{
"countries":{
"ZAF":{
"count":2
}
},
"checkId":"144165083478491226"
}
}
数组2:
{
"0":{
"countries":{
"AIA":{
"count":2
}
},
"checkId":"144165083478491106"
},
"1":{
"countries":{
"BDI":{
"count":1
},
"IRN":{
"count":1
},
"ATA":{
"count":5
}
},
"checkId":"16835659691517226105"
}

}
我想找到两个数组之间的不匹配和共同元素。目前,我正在执行两个 for 循环来查找两个基于 checkid 的数组之间的匹配元素,但我无法从这两个中找到非常见元素。
一些代码片段
  array1.forEach(each => {
array2.forEach(compareTask => {
var teastEach = Object.entries(compareTask.countries);
if (each.checkId === compareTask.checkId) {
firstCount = each.count
secondCount = compareTask.count
countDifference = secondCount - firstCount
……
我能够获得常见的 checkid,但无法获得非常见的 checkid。
预期输出:
    {
"0":{
"countries":{
"ZAF":{
"count":2
}
},
"checkId":"144165083478491226"
},
"1":{
"countries":{
"AIA":{
"count":2
}
},
"checkId":"144165083478491106"
}
}

最佳答案

从评论看来您可以使用 Map()

object1 = { "0": { countries: { BDI: { count: 1, }, IRN: { count: 1, }, }, checkId: "16835659691517226105", }, "1": { countries: { ZAF: { count: 2, }, }, checkId: "144165083478491226", }, };
object2 = { "0": { countries: { AIA: { count: 2, }, }, checkId: "144165083478491106", }, "1": { countries: { BDI: { count: 1, }, IRN: { count: 1, }, ATA: { count: 5, }, }, checkId: "16835659691517226105", }, };

map = new Map();
arr = [Object.values(object1), Object.values(object2)].flat();
result = [
...arr
.reduce((r, o) => {
const dupli = r.get(o.checkId);
dupli ? r.delete(o.checkId) : r.set(o.checkId, o);
return r;
}, new Map())
.values(),
];
console.log(result);

关于javascript - 如何在 react 中找到两个嵌套数组之间的不匹配元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63349765/

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