Remove array element based on object property

后端 未结 12 1004
臣服心动
臣服心动 2020-11-22 08:19

I have an array of objects like so:

var myArray = [
    {field: \'id\', operator: \'eq\', value: id}, 
    {field: \'cStatus\', operator: \'eq\', value: cSta         


        
12条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 09:03

    You can use lodash's findIndex to get the index of the specific element and then splice using it.

    myArray.splice(_.findIndex(myArray, function(item) {
        return item.value === 'money';
    }), 1);
    

    Update

    You can also use ES6's findIndex()

    The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.

    const itemToRemoveIndex = myArray.findIndex(function(item) {
      return item.field === 'money';
    });
    
    // proceed to remove an item only if it exists.
    if(itemToRemoveIndex !== -1){
      myArray.splice(itemToRemoveIndex, 1);
    }
    

提交回复
热议问题