I have an array of objects like so:
var myArray = [
{field: \'id\', operator: \'eq\', value: id},
{field: \'cStatus\', operator: \'eq\', value: cSta
In ES6, just one line.
const arr = arr.filter(item => item.key !== "some value");
:)
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
.
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);
}
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.
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);
}
}
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>