在 JavaScript 中按特定属性过滤对象数组?

javascriptweb developmentobject oriented programming更新于 2025/11/11 3:56:17

使用 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 属性过滤对象数组。将考虑金额最大的对象。

示例

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

相关文章


有用资源