从具有最高值的对象返回属性

return property from object with the highest value

本文关键字:对象 返回 属性 最高值      更新时间:2023-09-26

我有以下内容:

$.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
});

我的目标是这样的:

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

highestNumb-var返回所有属性中的最高值,如何返回与最高值关联的属性,可能会出现两个属性具有相同最高值的情况。

highestNumb将返回94,但在这种情况下,我也想访问与94相关的属性cleanity。

假设您的对象是

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

你可以做:

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

请注意,如果两个属性具有相同的值,则会返回最先遇到的属性。

highestNumb将返回94,但我也想访问该属性在这种情况下与94清洁度相关。

你需要记住值最高的密钥

使其

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

演示

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