var obj={'one':1,'two':50,'three':75,'four':12}
这是一个对象,我希望输出为“three”:75,这是键值对的最大值。 我的限制是不使用for循环和任何库。 是否可能?
var obj={'one':1,'two':50,'three':75,'four':12}
顺便说一下,我找到了另一种解决方案,但它也使用了循环。
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];
我用循环写的解决方案。
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);
for
循环。 - Andy如果你愿意稍微改变一下你的数据结构,就可以做到这点。不要使用一个对象,而是使用对象数组,然后使用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
你可以根据给定对象的结构创建一个新的对象
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);
while
循环呢? - user663031