从具有最小值的javascript对象获取密钥

时间:2016-06-24 07:51:09

标签: javascript

我正在尝试从具有最小值的javascript对象获取密钥。

var myobj = {"1632":45,"1856":12,"1848":56,"1548":34,"1843":88,"1451":55,"4518":98,"1818":23,"3458":45,"1332":634,"4434":33};

我必须得到具有最小价值的钥匙。即:

1856

努力争取。我是对象操纵的新手。

5 个答案:

答案 0 :(得分:2)

Cou可以使用Array#reduce



var object = { "1632": 45, "1856": 12, "1848": 56, "1548": 34, "1843": 88, "1451": 55, "4518": 98, "1818": 23, "3458": 45, "1332": 634, "4434": 33 },
    key = Object.keys(object).reduce(function (r, a, i) {
        return !i || +object[a] < +object[r] ? a : r;
    }, undefined);

console.log(key);
&#13;
&#13;
&#13;

答案 1 :(得分:2)

迭代对象属性并根据最小值获取密钥。

var myjson = {
  "1632": 45,
  "1856": 12,
  "1848": 56,
  "1548": 34,
  "1843": 88,
  "1451": 55,
  "4518": 98,
  "1818": 23,
  "3458": 45,
  "1332": 634,
  "4434": 33
};

// get object keys array
var keys = Object.keys(myjson),
  // set initial value as first elemnt in array
  res = keys[0];

// iterate over array elements
keys.forEach(function(v) {
  // compare with current property value and update with the min value property
  res = +myjson[res] > +myjson[v] ? v : res;
});

console.log(res);

答案 2 :(得分:1)

你可以试试这个:

&#13;
&#13;
var xx={"1632":45,"1856":12,"1848":56,"1548":34,"1843":88,"1451":55,"4518":98,"1818":23,"3458":45,"1332":634,"4434":33};


var z=_.keys(_.pick(xx, function(value, key, object) {
return (value==_.min(_.values(xx)));  
}))[0];

document.getElementById("my_div").innerHTML=z;
&#13;
<script src="http://underscorejs.org/underscore-min.js"></script>

<div id="my_div"> </div>
&#13;
&#13;
&#13;

已使用第三方库underscore.js。你应该试一试:

http://underscorejs.org/underscore-min.js

答案 3 :(得分:0)

学习者通过for循环的方法:

ArrayBuffer(3)

更具功能性的方法:

var myobj = {"1632":45,"1856":12,"1848":56,"1548":34,"1843":88,"1451":55,"4518":98,"1818":23,"3458":45,"1332":634,"4434":33};

// Get the keys of myobj so we can iterate through it
var keys = Object.keys(myobj);

// Iterate through all the key values
var minimumKey = keys[0];
for(var i = 1; i < keys.length; i++){
    var minimum = myobj[minimumKey];
    var value = myobj[keys[i]];
    if(minimum > value) minimumKey = keys[i];
}

console.log(minimumKey, myobj[minimumKey]);

答案 4 :(得分:0)

又甜又甜:

let key = Object.keys(obj).reduce((key, v) => obj[v] < obj[key] ? v : key);