Remove array element based on object property

后端 未结 12 762
臣服心动
臣服心动 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:01

    In ES6, just one line.

    const arr = arr.filter(item => item.key !== "some value");
    

    :)

    0 讨论(0)
  • 2020-11-22 09:02

    Here's another option using jQuery grep. Pass true as the third parameter to ensure grep removes items that match your function.

    users = $.grep(users, function(el, idx) {return el.field == "money"}, true)
    

    If you're already using jQuery then no shim is required, which is could be useful as opposed to using Array.filter.

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2020-11-22 09:07

    One possibility:

    myArray = myArray.filter(function( obj ) {
        return obj.field !== 'money';
    });
    

    Please note that filter creates a new array. Any other variables referring to the original array would not get the filtered data although you update your original variable myArray with the new reference. Use with caution.

    0 讨论(0)
  • 2020-11-22 09:10

    Iterate through the array, and splice out the ones you don't want. For easier use, iterate backwards so you don't have to take into account the live nature of the array:

    for (var i = myArray.length - 1; i >= 0; --i) {
        if (myArray[i].field == "money") {
            myArray.splice(i,1);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 09:10

    Using the lodash library:

    var myArray = [
        {field: 'id', operator: 'eq', value: 'id'}, 
        {field: 'cStatus', operator: 'eq', value: 'cStatus'}, 
        {field: 'money', operator: 'eq', value: 'money'}
    ];
    var newArray = _.remove(myArray, function(n) {
      return n.value === 'money';;
    });
    console.log('Array');
    console.log(myArray);
    console.log('New Array');
    console.log(newArray);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>

    0 讨论(0)
提交回复
热议问题