如何通过特定属性对 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