id不相同时2个对象数组的差异

时间:2018-07-10 18:53:33

标签: javascript arrays

我有2个数组,arr1从数据库中检索,arr2作为请求正文发送。我试图获取两个数组之间的差异,但由于从数据库中的id不是字符串,所以出现错误。如何对数组中的id进行字符串化处理,以便正确过滤?

arr1 = [
   { id: 125ddgs34, name: ‘dgsgs’  }, 
   { id: 356kfjj1235, name: ‘adhkdh’  }, 
   { id: 87hjsgffjj, name: ‘fshjyy’  }, 
]

arr2 = [
  { id: ‘125ddgs34’, name: ‘dgsgs’  }, 
  { id: ‘356kfjj1235’, name: ‘adhkdh’  }, 
]

let difference = arr1.filter(x => !arr2.some(x2 => {
    console.log(x.id, "=========")
    console.log((x2.id, "======"))
}));

1 个答案:

答案 0 :(得分:0)

如果您使用的是“ mongodb”,请尝试以下操作:

arr1 = [
   { id: ObjectId("507f1f77bcf86cd799439011"), name: ‘dgsgs’  }, 
   { id: ObjectId("507f1f77bcf86cd799439012"), name: ‘adhkdh’  }, 
   { id: ObjectId("507f1f77bcf86cd799439013"), name: ‘fshjyy’  }, 
]