找到子对象的最大值 [英] find max value of a child object
问题描述
在javascript中查找子对象的最大值的优雅方法是什么?
What would be an elegant way to find the max value of a child object in javascript?
示例:
找到此对象的最大数量值(此处显示为json):
find the max quantity value of this object (here shown as json):
{"density":[
{"price":1.22837, "quantity":48201},
{"price":1.39837, "quantity":28201},
{"price":1.40107, "quantity":127011},
{"price":1.5174, "quantity":75221},
{"price":1.60600, "quantity":53271}
]}
感谢您的任何建议!
PS:只是为了澄清:当然我可以循环,但我认为会有一个更优雅的方式...
PS: just to clarify: of course i could loop through, but i thought there would be a more elegant way ...
推荐答案
这是 reduce
Array原型的方法:
There's the reduce
method of the Array prototype:
var arr = JSON.parse(objstring)["density"];
var max = arr.reduce(function(a, b) {
return Math.max(a, b.quantity);
}, 0);
另一个解决方案是
var max = Math.max.apply(null, arr.map(function(item){
return item["quantity"];
}));
对于更优雅的方式,有功能库提供getter工厂函数和更多Array方法。具有此类库的解决方案可能看起来像
For more "elegant" ways there are functional libraries which provide getter factory functions and more Array methods. A solution with such a library could look like
var max = arr.get("quantity").max();
这与上面的完全相同,但表达更好。
which would do exactly the same as the above one, but nicer expressed.
这篇关于找到子对象的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!