javascript - 如何比较两个对象数组以找出差异
问题描述
实际上,当我比较两个对象数组时,我遇到了一个迭代问题。
旧数组:
[{uuid:'a'}, {uuid:'b'}, {uuid:'c'}]
阵列新:
[{uuid:'a'}, {uuid:'e'}, {uuid:'f'}]
我要做的是在以下逻辑下调用 api:
比较 'new' 和 'old' 得到结果:
[{name:1, uuid:'e'}, {name:1, uuid:'f'}]
然后一一调用POST api添加新的uuid:'e'和'f'
比较 '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);
解决方案
使用过滤器和映射,您可以在旧数组中获得唯一性
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;
}
推荐阅读
- postgresql - 如何在postgres中转置查询结果
- python - Space separated file to Pandas when values have spaces
- snowflake-cloud-data-platform - VOLATILE | IMMUTABLE behavior in snowflake
- java - How to customize expireAfterWrite for concrete cache if I use cacheBuilder?
- r - R: Compare each element with all the other elements below in a list using foreach, parallel and doParallel
- android - PeriodicWorkRequest not working periodically
- python - Django forms stop form processing on ValidationError
- php - phpMyAdmin Database Not found
- python - 关于重新加载模块的说明
- nginx - Nginx : 允许 Googlebot 并检查其他访问者是否经过身份验证