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

Lọc mảng đối tượng theo thuộc tính cụ thể trong JavaScript

Dùng map() với toán tử ternary (?) so sánh thuộc tính amount tại cùng vị trí giữa 2 mảng.

Ví dụ

let firstCustomerDetails = [
    {firstName: 'John', amount: 100},
    {firstName: 'David', amount: 50},
    {firstName: 'Bob', amount: 80}
];

let secondCustomerDetails = [
    {firstName: 'John', amount: 400},
    {firstName: 'David', amount: 70},
    {firstName: 'Bob', amount: 40}
];

var result = firstCustomerDetails.map((obj, index) => 
    obj.amount > secondCustomerDetails[index].amount ? obj : secondCustomerDetails[index]
);

console.log(result);

Cách chạy

node demo.js

Kết quả

[
  { firstName: 'John', amount: 400 },
  { firstName: 'David', amount: 70 },
  { firstName: 'Bob', amount: 80 }
]

Lưu ý: Cách này giả định 2 mảng cùng độ dài và cùng thứ tự. Dùng find() nếu cần so sánh theo key không theo vị trí.