Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to remove an object using filter() in JavaScript?
The filter() method creates a new array with elements that pass a test condition. It's commonly used to remove objects from arrays based on specific criteria.
Initial Array
Let's start with an array of objects where some have a details property and others don't:
let objectValue = [
{ "id": "101", "details": { "Name": "John", "subjectName": "JavaScript" }},
{ "id": "102", "details": { "Name": "David", "subjectName": "MongoDB" }},
{ "id": "103" }
];
console.log("Original array:");
console.log(objectValue);
Original array:
[
{
id: '101',
details: { Name: 'John', subjectName: 'JavaScript' }
},
{
id: '102',
details: { Name: 'David', subjectName: 'MongoDB' }
},
{ id: '103' }
]
Removing Objects Without details Property
Use filter() to keep only objects that have a details property:
let objectValue = [
{ "id": "101", "details": { "Name": "John", "subjectName": "JavaScript" }},
{ "id": "102", "details": { "Name": "David", "subjectName": "MongoDB" }},
{ "id": "103" }
];
let filteredObjects = objectValue.filter(obj => obj.details);
console.log("After filtering (objects with details only):");
console.log(filteredObjects);
After filtering (objects with details only):
[
{
id: '101',
details: { Name: 'John', subjectName: 'JavaScript' }
},
{
id: '102',
details: { Name: 'David', subjectName: 'MongoDB' }
}
]
Removing Objects by ID
You can also remove objects based on specific ID values:
let objectValue = [
{ "id": "101", "details": { "Name": "John", "subjectName": "JavaScript" }},
{ "id": "102", "details": { "Name": "David", "subjectName": "MongoDB" }},
{ "id": "103" }
];
// Remove object with id "102"
let filteredById = objectValue.filter(obj => obj.id !== "102");
console.log("After removing object with id '102':");
console.log(filteredById);
After removing object with id '102':
[
{
id: '101',
details: { Name: 'John', subjectName: 'JavaScript' }
},
{ id: '103' }
]
How filter() Works
The filter() method:
- Tests each element against a condition
- Returns
trueto keep the element,falseto remove it - Creates a new array without modifying the original
Conclusion
Use filter() to remove objects from arrays by defining conditions. It returns a new array containing only elements that pass the test, leaving the original array unchanged.
Advertisements
