如何找到对象的最大值,然后在javascript中返回values属性? [英] How do I find the max value of an object and then return that values property in javascript?
问题描述
我需要使用具有最大值的属性并返回该属性吗?从一个对象中的一个对象,如何在JS中完成呢?还是jQuery中有什么可以使它变得容易?
I need to take the property with the max value and return the property? From an object in an object, how can this be done in JS? or is there something in jQuery that would make it easy?
例如,对于总统",我需要返回路易丝"
So for example for "president", I need to return "Louise"
voteCount
{
president:
{
Bob: 3,
Mary: 1,
Cindy: 1,
Louise: 10,
Fred: 4,
Ivy: 1,
Nate: 1,
Oscar: 1,
Paulina: 1,
Tracy: 1,
Wesley: 1,
Steve: 1
},
vicePresident:
{
Devin: 1,
Hermann: 11,
John: 1,
Alex: 3,
Kerry: 2,
Mary: 1,
Oscar: 1,
Nate: 1,
Bob: 2,
Steve: 1,
Yvonne: 1,
Zane: 1
},
secretary:
{
Gail: 1,
Fred: 14,
Bob: 2,
Ivy: 3,
Mary: 1,
Nate: 1,
Devin: 1,
Oscar: 1,
Alex: 1,
Valorie: 1
},
treasurer:
{
Kerry: 2,
Ivy: 14,
Bob: 4,
Fred: 1,
Gail: 1,
Tracy: 1,
Xavier: 1,
Hermann: 1,
Mary: 1
}
}
推荐答案
您可以获取密钥并根据值进行缩减
You could get the keys and reduce based on the values
var key = Object.keys(voteCount.president).reduce(function(a, b) {
return voteCount.president[a] > voteCount.president[b] ? a : b;
});
̿'̿'̿\̵͇̿̿\з=(•̪●)=ε/̵͇̿̿/'̿'̿̿
̿'̿'̿\̵͇̿̿\з=(•̪●)=ε/̵͇̿̿/'̿'̿ ̿
Object.keys
获取数组中的所有键,如Bob,Mary,Cindy等.
然后Array.reduce
缩小该数组,直到只剩下一个值为止,因为它使用了这样的条件
Object.keys
gets all the keys, as in Bob, Mary, Cindy etc. in an array.
Then Array.reduce
reduces that array until only one value is left, and because it uses a condition like this
obj[key1] > obj[key2] ? key1 : key2;
它基本上说如果Bob的值大于Mary的值,则返回Bob,在下一次迭代测试中,将Bob的值与Cindy进行比较,并返回较大的值,这样更易读
it basically says if the value of Bob is greater than the value of Mary, return Bob, and on the next iteration test the value of Bob against Cindy and return whichever is greater, more readable like this
if ( obj['Bob'] > obj[Mary] ) {
return 'Bob';
} else {
return 'Mary';
}
并执行此操作,直到仅保留具有最大价值的名称为止.
and it does that until only the name with the greatest value remains.
这篇关于如何找到对象的最大值,然后在javascript中返回values属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!