2015-11-16 36 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];