如何通过在JavaScript对象中的多个键/值对中找到最小值来选择键/值对? [英] How do I select a key/value pair by finding the smallest value in a number of key/value pairs in a JavaScript object?

查看:80
本文介绍了如何通过在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]

这篇关于如何通过在JavaScript对象中的多个键/值对中找到最小值来选择键/值对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆