2015-11-16 37 views
2
var obj={'one':1,'two':50,'three':75,'four':12} 

這是我希望輸出爲'three'的對象:75,這是對象中最大值的關鍵值對。 我的約束不是用於循環和任何庫。 可能嗎?從對象獲取最大key.value對,無for循環

+1

這是不可能的,除非您有權訪問該項目時,將值插入到對象中,然後您可以始終保持本地最大值。但除此之外,這是不可能的 – LiranBo

+0

你必須通過項目 – MoLow

+0

這是可能的,但不是最好/可靠的方式。 [Math.max.apply(Math.max,JSON.stringify(obj).match(/ \ d +/g));](https://jsfiddle.net/tusharj/cc90uctu/) – Tushar

回答

2

我用循環的解決方案。

var obj = {'one':1,'two':50,'three':75,'four':12} ; 

var maxKey = Object.keys(obj).reduce(function (prev, next){ 
       return obj[prev] > obj[next] ? prev : next; 
      }); 

var result = {}; 
result[maxKey] = obj[maxKey]; 

console.log(result); 
+1

但是,這正是一個循環。 –

+0

@torazaburo,OP特別請求不要'for'循環。 – Andy

+0

但是,這裏的問題是隻有值被輸出,而不是關鍵_和_值。 – Andy

1

如果你願意改變你的數據結構,你也許可以做到這一點。取而代之的對象有對象的數組,然後用filter基於最大值搶對象:

var arr = [ 
    { key: 'one', value: 1 }, 
    { key: 'two', value: 50 }, 
    { key: 'three', value: 75 }, 
    { key: 'four', value: 12 } 
]; 

var max = Math.max.apply(null, arr.map(function (el) { 
    return el.value; 
})); 

var output = arr.filter(function (el) { 
    return el.value === max; 
})[0]; 

console.log(out.key + ': ' + out.value); // three: 75 

DEMO

0

就可以使這種結構的新對象的形式給定對象

var newObject = [ 
    { key: 'one', value: 1 }, // key value structure 
    { key: 'two', value: 50 }, 
    { key: 'three', value: 75 }, 
    { key: 'four', value: 12 } 
]; 

var obj = { 
 
    'one': 1, 
 
    'two': 50, 
 
    'three': 75, 
 
    'four': 12 
 
} 
 

 
var newObJ = Object.keys(obj).map(function (key) { 
 
    return { 
 
     "key": key, 
 
      "value": obj[key] 
 
    } 
 
}); 
 
var max = Math.max.apply(null, newObJ.map(function (el) { 
 
    return el.value; 
 
})); 
 

 
var output = newObJ.filter(function (el) { 
 
    return el.value === max; 
 
})[0]; 
 

 
document.write(output.key + ': ' + max);

3

順便說一句,我找到了另一種解決方案,但它也使用循環。

var obj = {'one': 1, 'two': 50, 'three': 75, 'four': 12}; 

var maxKey = Object.keys(obj).sort(function (a, b) { 
    return obj[a] < obj[b]; 
})[0]; 

var result = {}; 
result[maxKey] = obj[maxKey];