简体   繁体   中英

return property from object with the highest value

I have the following:

$.ajax({
          url: 'https://api.m.hostelworld.com/1.5/properties/'+propID+'/?update-cache=true', 
          dataType: 'json', 
          headers: {
            "Accept-Language": lang 
          },
          success: function(json) { 
            var numb = 0;
            var property;
            for (var key in json.rating) {
                numb = Math.max(numb, json.rating[key]);
                if(json.rating[key] == numb){
                     console.log(property with the highestNumb);
                }
            }
            highestNumb = numb;
            return highestNumb;

          }, cache: false
});

and my object is like this:

rating":{
  "overall": 92,
  "atmosphere": 93,
  "cleanliness": 94,
  "facilities": 89,
  "staff": 94,
  "security": 92,
  "location": 88,
  "valueForMoney": 92
},

highestNumb var returns the highest value out of all of them, how can I return the property associated to the highest value, there might be a case where 2 properties will have the same highest value.

highestNumb will return 94 but I also want to access the property associated to 94 in this case cleanliness.

Assuming your object is

var obj = {"rating":{
  "overall": 92,
  "atmosphere": 93,
  "cleanliness": 94,
  "facilities": 89,
  "staff": 94,
  "security": 92,
  "location": 88,
  "valueForMoney": 92
} // ...}

You can do:

var maxValue = -1;
var maxKey;
for (var key in obj.rating) {
   if (obj.rating[key] > maxValue) {
     maxValue = obj.rating[key];
     maxKey = key;
   }
} 

console.log(maxKey) // cleanliness

Note that if two properties have the same value, this will return the one that was encountered first.

highestNumb will return 94 but I also want to access the property associated to 94 in this case cleanliness.

You need to remember the key with highest value

Make it

  success: function(json) { 
        var numb = 0;
        var highestProp;     
        for (var key in json.rating) {
            if ( json.rating[key] > numb )
            {
               numb = json.rating[key];
               highestProp = key;
            }                
        }
        return highestProp;
      }

DEMO

 var rating = { "overall": 92, "atmosphere": 93, "cleanliness": 94, "facilities": 89, "staff": 94, "security": 92, "location": 88, "valueForMoney": 92 }; var numb = 0; var highestProp; for (var key in rating) { if (rating[key] > numb) { numb = rating[key]; highestProp = key; } } alert("highest property " + highestProp ); alert("highest value " + numb ); 

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