Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Duyệt vòng lặp for trong đối tượng để lấy bản ghi CustomerId lẻ

Duyệt mảng đối tượng, kiểm tra customerId % 2 != 0 để lọc ID lẻ.

Ví dụ

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

Cách chạy

node demo.js

Kết quả

Customer ID: 101
Customer Name: John
-----------------------------------
Customer ID: 103
Customer Name: Mike
-----------------------------------

Cách hiện đại (ES6+):

customerDetails
    .filter(c => c.customerId % 2 !== 0)
    .forEach(c => console.log(`ID: ${c.customerId}, Name: ${c.customerName}`));