remove objects from array by object property

前端 未结 13 2714
抹茶落季
抹茶落季 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:54

    If you just want to remove it from the existing array and not create a new one, try:

    var items = [{Id: 1},{Id: 2},{Id: 3}];
    items.splice(_.indexOf(items, _.find(items, function (item) { return item.Id === 2; })), 1);
    
    0 讨论(0)
  • 2020-11-22 17:57

    Loop in reverse by decrementing i to avoid the problem:

    for (var i = arrayOfObjects.length - 1; i >= 0; i--) {
        var obj = arrayOfObjects[i];
    
        if (listToDelete.indexOf(obj.id) !== -1) {
            arrayOfObjects.splice(i, 1);
        }
    }
    

    Or use filter:

    var newArray = arrayOfObjects.filter(function(obj) {
        return listToDelete.indexOf(obj.id) === -1;
    });
    
    0 讨论(0)
  • 2020-11-22 17:57
    var arrayOfObjects = [{id:'abc',name:'oh'}, // delete me
                          {id:'efg',name:'em'}, // delete me
                          {id:'hij',name:'ge'}] // all that should remain
    

    as per your answer will be like this. when you click some particular object send the index in the param for the delete me function. This simple code will work like charm.

    function deleteme(i){
        if (i > -1) {
          arrayOfObjects.splice(i, 1);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 17:58

    findIndex works for modern browsers:

    var myArr = [{id:'a'},{id:'myid'},{id:'c'}];
    var index = myArr.findIndex(function(o){
      return o.id === 'myid';
    })
    if (index !== -1) myArr.splice(index, 1);
    
    0 讨论(0)
  • 2020-11-22 18:02

    You can use filter. This method always returns the element if the condition is true. So if you want to remove by id you must keep all the element that doesn't match with the given id. Here is an example:

    arrayOfObjects = arrayOfObjects.filter(obj => obj.id != idToRemove)

    0 讨论(0)
  • 2020-11-22 18:04

    You can remove an item by one of its properties without using any 3rd party libs like this:

    var removeIndex = array.map(item => item.id)
                           .indexOf("abc");
    
    ~removeIndex && array.splice(removeIndex, 1);
    
    0 讨论(0)
提交回复
热议问题