How do I select a key/value pair by finding the smallest value in a number of key/value pairs in a JavaScript object?

拜拜、爱过 提交于 2019-12-11 13:21:01

问题


I have an object that looks like this:

var obj = {
  thingA: 5,
  thingB: 10,
  thingC: 15
}

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.


回答1:


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]

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]



回答2:


here is a simple function that can do exactly what you wanted -

function getSmallest(obj)
{
    var min,key;
    for(var k in obj)
    {
        if(typeof(min)=='undefined')
        {
            min=obj[k];
            key=k;
            continue;
        }
        if(obj[k]<min)
        {
            min=obj[k]; 
            key=k;
        }
    }
    return key+':'+min;
}



//test run
var obj={thingA:5,thingB:10,thingC:15};
var smallest=getSmallest(obj)//thingA:5


来源:https://stackoverflow.com/questions/11713574/how-do-i-select-a-key-value-pair-by-finding-the-smallest-value-in-a-number-of-ke

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!