[javascript] Remove array element based on object property

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?

This question is related to javascript jquery arrays object properties

The answer is


We can remove the element based on the property using the below 2 approaches.

  1. Using filter method
testArray.filter(prop => prop.key !== 'Test Value')
  1. Using splice method. For this method we need to find the index of the propery.
const index = testArray.findIndex(prop => prop.key === 'Test Value')
testArray.splice(index,1)

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);
}

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.


Using lodash library it is simple as this

_.remove(myArray , { field: 'money' });

Using the lodash library:

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


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.


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);
    }
}

In ES6, just one line.

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

:)


Following is the code if you are not using jQuery. Demo

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

alert(myArray.length);

for(var i=0 ; i<myArray.length; i++)
{
    if(myArray[i].value=='money')
        myArray.splice(i);
}

alert(myArray.length);

You can also use underscore library which have lots of function.

Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support


Based on some comments above below is the code how to remove an object based on a key name and key value

 var items = [ 
  { "id": 3.1, "name": "test 3.1"}, 
  { "id": 22, "name": "test 3.1" }, 
  { "id": 23, "name": "changed test 23" } 
  ]

    function removeByKey(array, params){
      array.some(function(item, index) {
        return (array[index][params.key] === params.value) ? !!(array.splice(index, 1)) : false;
      });
      return array;
    }

    var removed = removeByKey(items, {
      key: 'id',
      value: 23
    });

    console.log(removed);

jAndy's solution is probably best, but if you can't rely on filter you could do something like:

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

myArray.remove_key = function(key){
    var i = 0, 
        keyval = null;
    for( ; i < this.length; i++){
        if(this[i].field == key){
            keyval = this.splice(i, 1);
            break;
        }
    }
    return keyval;
}

Say you want to remove the second object by it's field property.

With ES6 it's as easy as this.

myArray.splice(myArray.findIndex(item => item.field === "cStatus"), 1)

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to properties

Property 'value' does not exist on type 'EventTarget' How to read data from java properties file using Spring Boot Kotlin - Property initialization using "by lazy" vs. "lateinit" react-router - pass props to handler component Specifying trust store information in spring boot application.properties Can I update a component's props in React.js? Property getters and setters Error in Swift class: Property not initialized at super.init call java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US How to use BeanUtils.copyProperties?