Remove array of objects from another array of objects

前端 未结 4 1897
情话喂你
情话喂你 2021-02-06 11:17

Assume we have the following arrays of objects to be compared based on property id:

a = [{\'id\':\'1\', \'name\':\'a1\'}, {\'id\':\'2\', \'name\':\'         


        
4条回答
  •  终归单人心
    2021-02-06 11:52

    How about this solution? It assumes that 'b' is also an array so for each element of 'a' you check if there is a matching object in 'b'. If there is a matching object then return a false in the filter function so that that element is discarded.

    var a = [{
      'id': '1',
      'name': 'a1'
    }, {
      'id': '2',
      'name': 'a2'
    }, {
      'id': '3',
      'name': 'a3'
    }]
    var b = [{
      'id': '2',
      'name': 'a2'
    }]
    
    var c = a.filter(function(objFromA) {
      return !b.find(function(objFromB) {
        return objFromA.id === objFromB.id
      })
    })
    
    console.log(c)

提交回复
热议问题