如何对比两个对象数组,找出全键值组合唯一的新增对象
问题:对比价格数组并找出需新增的全键唯一对象
需求说明
每周对比两个价格数据库的对象数组,找出newPrices中与oldPrices相比,date、price、locationId三个键值组合完全唯一的对象,将这些对象添加到旧数据库。
示例数据
旧数据库数据(oldPrices)
const oldPrices = [ {"date": "07-07-2022", "price": 129, "locationId": 1 }, {"date": "08-07-2022", "price": 139, "locationId": 1 }, {"date": "08-07-2022", "price": 139, "locationId": 2 } ];
新数据库数据(newPrices)
const newPrices = [ {"date": "07-07-2022", "price": 139, "locationId": 1 }, {"date": "08-07-2022", "price": 139, "locationId": 1 }, {"date": "08-07-2022", "price": 139, "locationId": 2 } ];
期望输出
[{"date": "07-07-2022", "price": 139, "locationId": 1 }]
当前代码问题
现有代码仅校验price字段是否相同,无法识别三个键值组合的差异,导致输出为空数组。
当前代码:
var data1 = {{(table17.data)}}; var data2 = {{ formatDataAsArray(table18.data) }}; const oldPrices = data1.map (({date, price, locationId}) => ({date, price, locationId})); const newPrices = data2.map (({date, price, locationId}) => ({date, price, locationId})); function getDifference(array1, array2) { return array1.filter(object1 => { return !array2.some(object2 => { return object1.price === object2.price; }); }); } const difference = [ ...getDifference(oldPrices, newPrices), ...getDifference(newPrices, oldPrices) ]; console.log(difference)
修改后的代码
调整对比逻辑,同时校验三个字段的组合匹配性,并只提取newPrices中不在oldPrices里的对象:
var data1 = {{(table17.data)}}; var data2 = {{ formatDataAsArray(table18.data) }}; const oldPrices = data1.map (({date, price, locationId}) => ({date, price, locationId})); const newPrices = data2.map (({date, price, locationId}) => ({date, price, locationId})); // 校验date、price、locationId三个字段的组合是否完全一致 function getNewUniqueItems(newArr, oldArr) { return newArr.filter(newItem => { return !oldArr.some(oldItem => newItem.date === oldItem.date && newItem.price === oldItem.price && newItem.locationId === oldItem.locationId ); }); } // 获取需要添加到旧数据库的新增对象 const newUniqueItems = getNewUniqueItems(newPrices, oldPrices); console.log(newUniqueItems);
代码说明
getNewUniqueItems函数遍历新数组,通过some检查旧数组中是否存在三个字段完全匹配的对象- 若不存在该匹配项,则将其标记为需要新增的对象
- 仅单向对比新数组到旧数组,更贴合需求逻辑
内容的提问来源于stack exchange,提问作者leonleprofessionnel
相关产品推荐
相关产品推荐

