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

假设我们需要按数量属性过滤对象数组。考虑数量最多的一个。

示例

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