获取Javascript中具有最高值的对象键

获取Javascript中具有最高值的对象键

本文介绍了获取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)
  • Create an array of keys: Object.keys(object)
  • Sort this array based on value: sort((a,b)=> object[b] - object[a])
  • Get necessary values: 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中具有最高值的对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 13:47