如何透過特定屬性對 JavaScript 中的物件陣列進行篩選?


結合三元運算子 (?) 使用 map() 概念。以下是我們的物件陣列 −

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}
];

假設我們需要按 amount 屬性過濾物件陣列。其中 amount 最大值的物件被認為是符合要求的物件。

示例

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 output = firstCustomerDetails.map((key, position) =>
key.amount > secondCustomerDetails[position].amount ? key :
secondCustomerDetails[position]
);
console.log(output);

要執行以上程式,你需要使用以下命令 −

node fileName.js.

在此,我的檔名是 demo83.js。

輸出

這將產生以下輸出 −

PS C:\Users\Amit\JavaScript-code> node demo83.js
[
   { firstName: 'John', amount: 400 },
   { firstName: 'David', amount: 70 },
   { firstName: 'Bob', amount: 80 }
]

更新時間: 07-Sep-2020

513 次瀏覽

啟動你的 職業

完成課程,獲得認證

開始
廣告
© . All rights reserved.