javascript - 根据其中一个键的条件从数组中获取单个对象
问题描述
我有一个对象数组,我想只获取数量最多的对象,在这个例子中是 'id': 4 的对象,并尝试使用 javascript 的 filter 属性,但我没有实现它,否则我能做到这一点吗?
[
{
"id": 1,
"quantity": 10,
"price": 80
},
{
"id": 2,
"quantity": 30,
"price": 170
},
{
"id": 3,
"quantity": 50,
"price": 230
},
{
"id": 4,
"quantity": 100,
"price": 100
}
]
解决方案
在这种情况下,reduce
是正确的选择:
const most = array.reduce((a, b) => a.quantity > b.quantity ? a : b);
推荐阅读
- python - Django - 如何将 DeleteView 限制为对象所有者
- django - 如何在不明确填写 PasswordResetForm 的情况下向用户发送电子邮件以重置密码?
- spring - 如何模拟 jdbctemplate.query() 方法?
- swift - 将 Xcode MVC 项目导出到 .framework 文件
- android - 阻止 Decimal EditText 获得对启动的关注
- sql - 触发器postgresql中的距离计算
- node.js - 将记录插入数据库,同时通知用户在 node.js 中插入或失败的记录数
- html - 下拉菜单出现问题,因为它没有出现在悬停时(只是一个 html-css 模板)
- php - PHP ssh2_exec() 不执行 iptables 命令
- python - Python 2.6.6 - 如何以表格形式打印具有对齐列的列表?