首页 > 解决方案 > 根据其中一个键的条件从数组中获取单个对象

问题描述

我有一个对象数组,我想只获取数量最多的对象,在这个例子中是 '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
  }
]

标签: javascriptarraysecmascript-6javascript-objects

解决方案


在这种情况下,reduce是正确的选择:

const most = array.reduce((a, b) => a.quantity > b.quantity ? a : b);

推荐阅读