Remove array of objects from another array of objects

前端 未结 4 1895
情话喂你
情话喂你 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:53

    First, you build just a map of the ids you want to delete. Then, you filter your first array with it, like that:

    var a = [{
      'id': '1',
      'name': 'a1'
    }, {
      'id': '2',
      'name': 'a2'
    }, {
      'id': '3',
      'name': 'a3'
    }];
    var b = [{
      'id': '2',
      'name': 'a2'
    }];
    
    var idsToDelete = b.map(function(elt) {return elt.id;});
    var result = a.filter(function(elt) {return idsToDelete.indexOf(elt.id) === -1;});
    console.log(result)

提交回复
热议问题