如何透過特定屬性對 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 }
]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP