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

时间:2016-04-13 13:09:51

标签: javascript

我有以下内容:

$.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返回所有值中的最高值,如何返回与最高值关联的属性,可能存在2个属性具有相同最高值的情况。

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

2 个答案:

答案 0 :(得分:1)

假设您的对象是

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

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

答案 1 :(得分:1)

  

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

<强>样本

&#13;
&#13;
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 );
&#13;
&#13;
&#13;