本文介绍了获取Javascript中具有最高值的对象键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
想象一个这样的对象:
var values = {
"2": 1,
"53": 2,
"56": 4,
"57": 9,
"61": 2,
"62": 16,
"63": 2,
"398": 24,
...
}
我的目标是找到具有最高值的 10 个对象键.在这种情况下:398,然后是 62,依此类推(= [398, 62, ...]
).我知道如何将其放入数组中,但不知道如何接收属性键.
My goal is, to find the 10 object keys, which have the highest value. In this case: 398, then 62 and so on (= [398, 62, ...]
). I know how I can put this into an array, don't know how to receive the property key though.
重要提示:我无法更改格式,因为它是服务器响应.
Important: I can't change the format because it's a server response.
我尝试使用 for (key in values) {}
循环,但不知道如何继续.这个类似的问题,它的答案也帮不了我.
I tried with a for (key in values) {}
loop but have no idea how to move on.This similar question and it's answer couldn't really help me either.
推荐答案
如前所述:
- 创建一个键数组:
Object.keys(object)
- 根据值对数组进行排序:
sort((a,b)=> object[b] - object[a])
- 获取必要的值:
keys.slice(0,n)
var value = {2:1,53:2,56:4,57:9,61:2,62:16,63:2,398:24};
function getKeysWithHighestValue(o, n){
var keys = Object.keys(o);
keys.sort(function(a,b){
return o[b] - o[a];
})
console.log(keys);
return keys.slice(0,n);
}
console.log(getKeysWithHighestValue(value, 4))
这篇关于获取Javascript中具有最高值的对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!