js利用filter获取两个对象数组中相同和不同的元素对象(转)

原文:https://blog.csdn.net/m0_72200584/article/details/128075370

let array1 = 
[
  { id:'1',name:'liuqiang' }, 
  { id:'2',name:'zhaobo' }
]
let array2 = 
[
  { id:'1', name:'liuqiang', age:'45'}, 
  { id:'2', name:'zhaobo', age:'67' },
  { id:'3', name:'menglong', age:'57'}
]
 
//取不同的元素
let res = arr2.filter(item => !arr1.some(ele=> ele.id === item.id)) 
console.log(res) //{id: '3', name: 'ani', age: '17'}
//取相同的元素
let res2 = arr2.filter(item => arr1.some(ele=> ele.id === item.id))
console.log(res2) // {id: '1', name: 'zhangsan', age: '15'}
                     {id: '2', name: 'lisi', age: '16'}
posted @ 2022-12-14 18:52  pine007  阅读(468)  评论(0编辑  收藏  举报