简体   繁体   English

如何从数组中获取具有最大属性的对象?

[英]How to get object with largest property from array?

I have an array of objects, with each object containing other 'subobjects'. 我有一个对象数组,每个对象都包含其他“子对象”。 I need to return the subobject with the largest 'quality' property. 我需要返回具有最大“品质”属性的子对象。

The code below logs out all subobjects. 下面的代码注销所有子对象。 How do I only return the one with the largest quality? 如何只退回质量最高的那一款?

 var maxQuality = function(Arr) { Arr.forEach(function(obj, index) { Math.max.apply(Math, obj.products.map(function(subObj) { console.log(subObj); })) }); }, store = [ { products: [ { quality: 1, info: 'info 1' }, { quality: 2, info: 'info 2' }, { quality: 3, info: 'info 3' } ] } ], maxQualityProduct = maxQuality(store); 

You can do that using the reduce() method on the array 您可以使用数组上的reduce()方法做到这一点

 var products = [ { quality: 1, info: 'info 1' }, { quality: 2, info: 'info 2' }, { quality: 3, info: 'info 3' } ]; var highest = products.reduce(function(prev, current) { return prev.quality > current.quality ? prev : current }, {}); console.log(highest); 

Note that reduce takes two parameters - one is the callback and the second is the initial item that you start with called seed . 请注意, reduce需要两个参数-一个是回调,第二个是您以种子开始的初始项。 In this case, since we are only checking a flat value, a seed of an empty object will work fine since when the property quality is taken from it it would return undefined and that would be less than any of the other products. 在这种情况下,由于我们仅检查一个固定值,因此空对象的种子将正常工作,因为从中获取属性quality时,它将返回undefined ,并且将小于其他任何乘积。 However, for more complex structures or comparisons, you might need to give an actual item from the array as a seed. 但是,对于更复杂的结构或比较,您可能需要将数组中的实际项目作为种子。

Although the other .reduce answer probably gives you what you need, if the store array were to contain more than one object - not sure if that is something you will want/need - you could use this: 尽管另一个.reduce答案可能会满足您的需要,但是如果存储数组包含多个对象-不确定是否是您想要/需要的对象-您可以使用以下方法:

var maxQuality = function(storeArray) {
    function highestQuality(prev, curr) {
        return prev.quality > curr.quality ? prev : curr
    }

    return storeArray.map(function(obj) {
      return obj.products.reduce(highestQuality)
    }).reduce(highestQuality);
}

我想这可以归结为一个简单的Array.prototype.sort类的东西:

products.sort(( a, b ) => b.quality - a.quality )[ 0 ];

You can use following snippet: 您可以使用以下代码段:

 var maxQuality = function(Arr) { var result = undefined; for (var obj of store) { for (var product of obj.products) { if (!result || product.quality > result.quality) { result = product; } } } return result; }, store = [ { products: [ { quality: 1, info: 'info 1' }, { quality: 2, info: 'info 2' }, { quality: 3, info: 'info 3' } ] } ], maxQualityProduct = maxQuality(store); console.log(maxQualityProduct); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM