从一个对象数组,如何返回具有最高属性`a`的对象的属性`b`? [英] From an array of objects, how to return property `b` of the object that has the highest property `a`?
本文介绍了从一个对象数组,如何返回具有最高属性`a`的对象的属性`b`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从具有最高属性值 a
的对象获取属性 b
的值。
I need to get the value of the property b
from the object with the highest value of the property a
.
var myArr = [
{
a: 1,
b: 15
},
{
a: 2,
b: 30
}
];
我尝试了以下内容,但它只返回的最高值a
,而不是 b
。
I tried the following, but it just returns the highest value of a
, rather than of b
.
var res = Math.max.apply(Math,myArr.map(function(o){return o.a;});
var blah = getByValue(myArr);
推荐答案
使用 Array#reduce ,并在每次迭代时获取具有最高 a
值的对象:
Use Array#reduce, and on each iteration take the object with the highest a
value:
var myArr = [{"a":1,"b":15},{"a":2,"b":30}];
var result = myArr.reduce(function(o, o1) {
return o.a > o1.a ? o : o1;
}).b;
console.log(result);
这篇关于从一个对象数组,如何返回具有最高属性`a`的对象的属性`b`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文