根据其键之一的条件从数组中获取单个对象

时间:2018-07-27 20:22:55

标签: javascript arrays ecmascript-6 javascript-objects

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

4 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:2)

您可以按quantity对数组进行排序,然后从排序后的数组中获取第一项。

var a = [{
    "id": 1,
    "quantity": 10,
    "price": 80
}, {
    "id": 2,
    "quantity": 30,
    "price": 170
}, {
    "id": 3,
    "quantity": 50,
    "price": 230
}, {
    "id": 4,
    "quantity": 100,
    "price": 100
}]

a.sort((obj1, obj2)=> obj2.quantity - obj1.quantity)[0]
// {id: 4, quantity: 100, price: 100}

答案 2 :(得分:0)

这将映射JSON对象数组,并跟踪数量最大的一个的索引。

let indexOfHighest = 1
arrayOfObject.map((obj,index) = {
   if(obj.quantity > arrayOfObject[indexOfHighest].quantity)
   {
     indexOfHighest = index
   }

})

答案 3 :(得分:0)

只需提供另一个答案-使用math

let a = [
  {
    "id": 1,
    "quantity": 10,
    "price": 80
  },
  {
    "id": 2,
    "quantity": 30,
    "price": 170
  },
  {
    "id": 3,
    "quantity": 50,
    "price": 230
  },
  {
    "id": 4,
    "quantity": 100,
    "price": 100
  }
]

let result = a.find(function(item){ return item.quantity ===  Math.max.apply(Math,a.map(function(item){return item.quantity;})); })

console.log(result)

这将使用数学库查找最大数量,然后在具有该数量的数组中找到对象。并非最佳答案,而是解决问题的另一种方式:)