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
How to filter an object depending on the field\'s value in JavaScript?
Filtering objects by field values is a common JavaScript operation used in web applications. This technique allows you to extract specific data from arrays of objects based on certain criteria, such as filtering products by brand or employees by department.
Basic Syntax
The most efficient way to filter objects is using the filter() method:
const filteredArray = array.filter(item => item.fieldName === fieldValue);
array ? Collection of objects to filter
filter() ? JavaScript method that creates a new array with elements passing the test
item ? Current object being processed
fieldName ? Property name to check in each object
fieldValue ? Value to match against
Method 1: Using filter() Method
The filter() method is the most straightforward approach:
const products = [
{ id: 1, name: 'iPhone', brand: 'Apple', price: 999 },
{ id: 2, name: 'Galaxy S23', brand: 'Samsung', price: 799 },
{ id: 3, name: 'MacBook', brand: 'Apple', price: 1299 },
{ id: 4, name: 'ThinkPad', brand: 'Lenovo', price: 899 }
];
// Filter by brand
const appleProducts = products.filter(product => product.brand === 'Apple');
console.log('Apple products:', appleProducts);
// Filter by price range
const affordableProducts = products.filter(product => product.price
Apple products: [
{ id: 1, name: 'iPhone', brand: 'Apple', price: 999 },
{ id: 3, name: 'MacBook', brand: 'Apple', price: 1299 }
]
Products under $900: [
{ id: 2, name: 'Galaxy S23', brand: 'Samsung', price: 799 },
{ id: 4, name: 'ThinkPad', brand: 'Lenovo', price: 899 }
]
Method 2: Using Object.entries() for Dynamic Filtering
When you need to filter by any field dynamically:
const employees = [
{ name: 'John', department: 'IT', salary: 60000 },
{ name: 'Sarah', department: 'HR', salary: 55000 },
{ name: 'Mike', department: 'IT', salary: 65000 },
{ name: 'Emma', department: 'Finance', salary: 70000 }
];
function filterByField(array, fieldName, fieldValue) {
return array.filter(item => item[fieldName] === fieldValue);
}
// Dynamic filtering
const itEmployees = filterByField(employees, 'department', 'IT');
console.log('IT Department:', itEmployees);
const highSalary = employees.filter(emp => emp.salary > 60000);
console.log('High salary employees:', highSalary);
IT Department: [
{ name: 'John', department: 'IT', salary: 60000 },
{ name: 'Mike', department: 'IT', salary: 65000 }
]
High salary employees: [
{ name: 'Mike', department: 'IT', salary: 65000 },
{ name: 'Emma', department: 'Finance', salary: 70000 }
]
Method 3: Multiple Criteria Filtering
Filter objects using multiple conditions:
const books = [
{ title: 'JavaScript Guide', author: 'John Doe', year: 2023, genre: 'Programming' },
{ title: 'Web Design', author: 'Jane Smith', year: 2022, genre: 'Design' },
{ title: 'Node.js Essentials', author: 'John Doe', year: 2023, genre: 'Programming' },
{ title: 'CSS Mastery', author: 'Bob Wilson', year: 2021, genre: 'Design' }
];
// Multiple criteria
const recentProgrammingBooks = books.filter(book =>
book.genre === 'Programming' && book.year >= 2023
);
console.log('Recent Programming Books:', recentProgrammingBooks);
// Author and genre filter
const johnDoeBooks = books.filter(book =>
book.author === 'John Doe' && book.genre === 'Programming'
);
console.log('John Doe Programming Books:', johnDoeBooks);
Recent Programming Books: [
{ title: 'JavaScript Guide', author: 'John Doe', year: 2023, genre: 'Programming' },
{ title: 'Node.js Essentials', author: 'John Doe', year: 2023, genre: 'Programming' }
]
John Doe Programming Books: [
{ title: 'JavaScript Guide', author: 'John Doe', year: 2023, genre: 'Programming' },
{ title: 'Node.js Essentials', author: 'John Doe', year: 2023, genre: 'Programming' }
]
Interactive Example
Here's a complete browser example with dynamic filtering:
<!DOCTYPE html>
<html>
<head>
<title>Object Filtering Example</title>
<style>
table { border-collapse: collapse; width: 100%; margin: 10px 0; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: center; }
th { background-color: #f2f2f2; }
input, button { margin: 5px; padding: 8px; }
</style>
</head>
<body>
<h2>Product Filter Demo</h2>
<div>
<input type="text" id="brandFilter" placeholder="Enter brand name">
<button onclick="filterProducts()">Filter by Brand</button>
<button onclick="showAll()">Show All</button>
</div>
<table id="productTable">
<thead>
<tr>
<th>ID</th>
<th>Product Name</th>
<th>Brand</th>
<th>Price</th>
</tr>
</thead>
<tbody id="productBody">
</tbody>
</table>
<script>
const products = [
{ id: 1, name: 'iPhone 15', brand: 'Apple', price: 999 },
{ id: 2, name: 'Galaxy S24', brand: 'Samsung', price: 899 },
{ id: 3, name: 'MacBook Pro', brand: 'Apple', price: 1999 },
{ id: 4, name: 'ThinkPad X1', brand: 'Lenovo', price: 1299 },
{ id: 5, name: 'Surface Pro', brand: 'Microsoft', price: 1099 }
];
function renderProducts(productArray) {
const tbody = document.getElementById('productBody');
tbody.innerHTML = '';
if (productArray.length === 0) {
tbody.innerHTML = '<tr><td colspan="4">No products found</td></tr>';
return;
}
productArray.forEach(product => {
const row = `
<tr>
<td>${product.id}</td>
<td>${product.name}</td>
<td>${product.brand}</td>
<td>$${product.price}</td>
</tr>
`;
tbody.innerHTML += row;
});
}
function filterProducts() {
const brandInput = document.getElementById('brandFilter').value.trim();
if (!brandInput) {
alert('Please enter a brand name');
return;
}
const filtered = products.filter(product =>
product.brand.toLowerCase().includes(brandInput.toLowerCase())
);
renderProducts(filtered);
}
function showAll() {
document.getElementById('brandFilter').value = '';
renderProducts(products);
}
// Initialize table
renderProducts(products);
</script>
</body>
</html>
Comparison of Filtering Methods
| Method | Performance | Use Case | Complexity |
|---|---|---|---|
filter() |
Fast | Simple single/multiple criteria | Low |
| Dynamic filtering | Fast | Unknown field names at runtime | Medium |
| Multiple criteria | Fast | Complex filtering logic | Medium |
Key Points
Use
filter()for creating new arrays without modifying the originalChain multiple conditions with logical operators (&&, ||)
Consider case-insensitive matching with
toLowerCase()Use
includes()for partial string matches
Conclusion
Object filtering using field values is essential for data manipulation in JavaScript. The filter() method provides a clean, efficient way to extract specific objects based on criteria, making it perfect for search functionality, data analysis, and dynamic content display.
