如何通过在JavaScript对象中的多个键/值对中找到最小值来选择键/值对?
问题描述:
我有一个看起来像这样的对象:
I have an object that looks like this:
var obj = {
thingA: 5,
thingB: 10,
thingC: 15
}
基于5与其他键/值对相比最小值是一个事实,我希望能够选择键/值对thingA: 5
.
I would like to be able to select the key/value pair thingA: 5
based on the fact that 5 is the smallest value compared to the other key/value pairs.
答
内置的功能没有,但是:
Nothing built-in does that, but:
var minPair = Object.keys(obj).map(function(k) {
return [k, obj[k]];
}).reduce(function(a, b) {
return b[1] < a[1] ? b : a;
});
minPair // ['thingA', 5]
或者,没有ECMAScript 5扩展名:
Or, sans ECMAScript 5 extensions:
var minKey, minValue;
for(var x in obj) {
if(obj.hasOwnProperty(x)) {
if(!minKey || obj[x] < minValue) {
minValue = obj[x];
minKey = x;
}
}
}
[minKey, minValue] // ['thingA', 5]