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
Iteration of for loop inside object in JavaScript to fetch records with odd CustomerId?
In JavaScript, you can iterate through an array of objects using a for loop and filter records based on specific conditions. Here's how to fetch records with odd CustomerId values.
Array of Objects Structure
Let's start with an array containing customer objects:
var customerDetails = [
{
customerId: 101,
customerName: "John"
},
{
customerId: 102,
customerName: "David"
},
{
customerId: 103,
customerName: "Mike"
},
{
customerId: 104,
customerName: "Bob"
}
];
Using For Loop to Filter Odd CustomerIds
Use the modulo operator (%) to check if a CustomerId is odd. An odd number gives a remainder of 1 when divided by 2:
var customerDetails = [
{
customerId: 101,
customerName: "John"
},
{
customerId: 102,
customerName: "David"
},
{
customerId: 103,
customerName: "Mike"
},
{
customerId: 104,
customerName: "Bob"
}
];
for(var index = 0; index < customerDetails.length; index++){
if(customerDetails[index].customerId % 2 != 0){
console.log("Customer Id = " + customerDetails[index].customerId);
console.log("Customer Name = " + customerDetails[index].customerName);
console.log("-----------------------------------------------------------");
}
}
Customer Id = 101 Customer Name = John ----------------------------------------------------------- Customer Id = 103 Customer Name = Mike -----------------------------------------------------------
Alternative Approaches
You can also use modern JavaScript methods for the same result:
// Using filter() method
const oddCustomers = customerDetails.filter(customer => customer.customerId % 2 !== 0);
oddCustomers.forEach(customer => {
console.log(`Customer Id = ${customer.customerId}`);
console.log(`Customer Name = ${customer.customerName}`);
console.log("-----------------------------------------------------------");
});
Customer Id = 101 Customer Name = John ----------------------------------------------------------- Customer Id = 103 Customer Name = Mike -----------------------------------------------------------
How It Works
The condition customerId % 2 != 0 works because:
- 101 % 2 = 1 (odd number)
- 102 % 2 = 0 (even number)
- 103 % 2 = 1 (odd number)
- 104 % 2 = 0 (even number)
Conclusion
Using a for loop with the modulo operator is an effective way to filter array objects based on numeric conditions. The traditional for loop provides direct control over iteration, while modern methods like filter() offer cleaner syntax.
Advertisements
