Remove array element based on object property

2019-01-01 07:10发布

I have an array of objects like so:

var myArray = [
    {field: 'id', operator: 'eq', value: id}, 
    {field: 'cStatus', operator: 'eq', value: cStatus}, 
    {field: 'money', operator: 'eq', value: money}
];

How do I remove a specific one based on its property?

e.g. How would I remove the array object with 'money' as the field property?

10条回答
路过你的时光
2楼-- · 2019-01-01 07:27

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.

查看更多
一个人的天荒地老
3楼-- · 2019-01-01 07:32

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.

查看更多
无色无味的生活
4楼-- · 2019-01-01 07:34

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.

myArray.splice(myArray.findIndex(myArray, function(item) {
    return item.value === 'money';
}), 1);
查看更多
萌妹纸的霸气范
5楼-- · 2019-01-01 07:34
var myArray = [
    {field: 'id', operator: 'eq', value: id}, 
    {field: 'cStatus', operator: 'eq', value: cStatus}, 
    {field: 'money', operator: 'eq', value: money}
];
console.log(myArray.length); //3
myArray = $.grep(myArray, function(element, index){return element.field == "money"}, true);
console.log(myArray.length); //2

Element is an object in the array. 3rd parameter true means will return an array of elements which fails your function logic, false means will return an array of elements which fails your function logic.

查看更多
登录 后发表回答