Home > Web Front-end > JS Tutorial > How to Remove an Array Element Based on its Object Property in JavaScript?

How to Remove an Array Element Based on its Object Property in JavaScript?

Linda Hamilton
Release: 2024-11-26 04:36:09
Original
706 people have browsed it

How to Remove an Array Element Based on its Object Property in JavaScript?

Removing Array Elements Based on Object Property

In JavaScript, manipulating arrays of objects is a common scenario. Occasionally, you may need to remove specific elements from such arrays based on a particular property.

Consider the following scenario:

const myArray = [
  { field: 'id', operator: 'eq', value: id },
  { field: 'cStatus', operator: 'eq', value: cStatus },
  { field: 'money', operator: 'eq', value: money },
];
Copy after login

Objective: Remove the Array Element with 'money' as the Field Property

To achieve this, you can utilize the filter() method. This method creates a new array containing only the elements that satisfy a given condition.

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

In this case, the filter function checks whether the field property of each object is not equal to 'money'. If it is not, the object is included in the new array.

Note:

It's important to remember that filter() creates a new array. If you refer to the original array using other variables, they will not contain the filtered data, even if you update the reference of the original variable (e.g., myArray) with the new array. Use this method with caution, especially when dealing with complex data structures.

The above is the detailed content of How to Remove an Array Element Based on its Object Property in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template