hae*_*mse 5 javascript json max
在javascript中查找子对象的最大值的优雅方法是什么?
例:
找到此对象的最大数量值(此处显示为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}
]}
Run Code Online (Sandbox Code Playgroud)
谢谢你的建议!
PS:只是为了澄清:当然我可以循环,但我认为会有更优雅的方式......
Ber*_*rgi 10
这是reduceArray原型的方法:
var arr = JSON.parse(objstring)["density"];
var max = arr.reduce(function(a, b) {
return Math.max(a, b.quantity);
}, 0);
Run Code Online (Sandbox Code Playgroud)
另一种解决方案就是这样
var max = Math.max.apply(null, arr.map(function(item){
return item["quantity"];
}));
Run Code Online (Sandbox Code Playgroud)
对于更"优雅"的方式,有功能库提供了getter工厂函数和更多的Array方法.有这样一个库的解决方案可能看起来像
var max = arr.get("quantity").max();
Run Code Online (Sandbox Code Playgroud)
这将与上面的完全相同,但更好地表达.
| 归档时间: |
|
| 查看次数: |
4296 次 |
| 最近记录: |