remove objects from array by object property

前端 未结 13 2712
抹茶落季
抹茶落季 2020-11-22 17:40
var listToDelete = [\'abc\', \'efg\'];

var arrayOfObjects = [{id:\'abc\',name:\'oh\'}, // delete me
                      {id:\'efg\',name:\'em\'}, // delete me
            


        
13条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 17:44

    With lodash/underscore:

    If you want to modify the existing array itself, then we have to use splice. Here is the little better/readable way using findWhere of underscore/lodash:

    var items= [{id:'abc',name:'oh'}, // delete me
                      {id:'efg',name:'em'},
                      {id:'hij',name:'ge'}];
    
    items.splice(_.indexOf(items, _.findWhere(items, { id : "abc"})), 1);
    

    With ES5 or higher

    (without lodash/underscore)

    With ES5 onwards we have findIndex method on array, so its easy without lodash/underscore

    items.splice(items.findIndex(function(i){
        return i.id === "abc";
    }), 1);
    

    (ES5 is supported in almost all morden browsers)

    About findIndex, and its Browser compatibility

提交回复
热议问题