filter array of objects by another array of objects

后端 未结 4 1960
日久生厌
日久生厌 2020-12-08 23:22

I want to filter array of objects by another array of objects.

I have 2 array of objects like this:

const array = [
    { id: 1, name: \'a1\', sub: {         


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-08 23:55

    You can use Array.filter and then Array.some since the later would return boolean instead of the element like Array.find would:

    const a1 = [ { id: 1, name: 'a1', sub: { id: 6, name: 'a1 sub' } }, { id: 2, name: 'a2', sub: null }, { id: 3, name: 'a3', sub: { id: 8, name: 'a3 sub' } }, { id: 4, name: 'a4', sub: null }, { id: 5, name: 'a5', sub: { id: 10, name: 'a5 sub' } }, ]; 
    const a2 = [ { id: 1, name: 'a1', sub: { id: 6, name: 'a1 sub' } }, { id: 2, name: 'a2', sub: null }, { id: 5, name: 'a5', sub: { id: 10, name: 'a5 sub' } }, ];
    
    const result = a1.filter(({id, sub}) => !a2.some(x => x.id == id) && sub)
    
    console.log(result)

提交回复
热议问题