Iteration of for loop inside object in JavaScript to fetch records with odd CustomerId?


Let’s say the following is our object −

var customerDetails=
[
   {
      customerId:101,
      customerName:"John"
   },
   {
      customerId:102,
      customerName:"David"
   },
   {
      customerId:103,
      customerName:"Mike"
   },
   {
      customerId:104,
      customerName:"Bob"
   }
]

Use for loop with the following condition to display only odd CustomerID records −

for(var index=0;index<customerDetails.length;index++){
   if(customerDetails[index].customerId % 2 !=0){
      //
   }
}

Example

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("---------------------------------------------------
--------")
   }
   console.log("");
}

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo71.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo71.js
Customer Id=101
Customer Name=John
-----------------------------------------------------------
Customer Id=103
Customer Name=Mike
-----------------------------------------------------------

Updated on: 07-Sep-2020

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements