简体   繁体   中英

get key from a javascript object with minimum value

I am trying to get key from javascript object having a minium value.

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

i have to get the key which having minimum value. ie:

1856

trying hard to get. i am new with object manipulation.

Cou could use 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); 

Iterate over the object properties and get key based on min value.

 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); 

You may try this:

 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; 
 <script src="http://underscorejs.org/underscore-min.js"></script> <div id="my_div"> </div> 

A 3rd party library underscore.js has been used. you should try it:

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

Learner's approach by for-looping:

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]);

A more functional approach:

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

var minimum = Object.keys(myobj).map(function(key){
    return {
        "key": key,
        "value": myobj[key]
    }
}).sort(function(a, b){
    return a.value - b.value
})[0];

console.log(minimum);
console.log(minimum.key);
console.log(minimum.value);

简短而甜蜜:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM