在对象中查找具有最大值的键

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在对象中查找具有最大值的键相关的知识,希望对你有一定的参考价值。

假设我有一个对象:

{Angry: "1.0", Fearful: "0.0", Happy: "0.0", Neutral: "0.0", Sad: "0.0"}

如何找到值最大的属性的名称?例如,这里:答案应该是“愤怒”,因为它的值“1.0”是最大的。感谢您的投入!

答案
var maxValue = 0;
var keyVal;
var object = {Angry: "1.0", Fearful: "0.0", Happy: "0.0", Neutral: "0.0", Sad: 
"0.0"};
for (var key in object) {
    let tempValue = parseFloat(object[key]);
    if(maxValue < tempValue) {
          maxValue = tempValue;
          keyVal = key;
    }
}

console.log(keyVal);
// expected output: "Angry"
另一答案

您将需要遍历JSON对象的所有属性并比较每个值以查看哪个属性最大。这是实现这一目标的一种方法:

var guy1 = {Angry: "1.0", Fearful: "0.0", Happy: "0.0", Neutral: "0.0", Sad: "0.0"};
var guy2 = {Angry: "1.0", Fearful: "2.0", Happy: "0.0", Neutral: "0.0", Sad: "0.0"};
var guy3 = {Angry: "1.0", Fearful: "2.0", Happy: "4.0", Neutral: "0.0", Sad: "0.0"};

biggest(guy1);
biggest(guy2);
biggest(guy3);


function biggest(obj) {
   var max = 0;
   var emotion; 

   Object.keys(obj).forEach(function(e){
     if(max<Number(obj[e])) { max = Number(obj[e]); emotion = e; }
   });

   console.log(emotion, max);
}
另一答案

您可以在reduce上使用Object.keys,使用累加器对象来跟踪您找到的当前最高值。

const obj = {Angry: "1.0", Fearful: "0.0", Happy: "0.0", Neutral: "0.0", Sad: "0.0"}

const largest = Object.keys(obj).reduce((largest, key, i) => {
  obj[key] = parseFloat(obj[key])

  largest = obj[key] > largest.num
    ? { key, num: obj[key] }
    : largest

  return i === Object.keys(obj).length - 1 ? largest.key : largest
}, {
  key: null,
  num: 0
})

console.log(largest)
另一答案

你可以试试这个

let obj ={Angry: "1.0", Fearful: "0.0", Happy: "0.0", Neutral: "0.0", Sad: "0.0"}

let max= -Infinity;
let keyName;

for(let key in obj){
  let temp  = parseFloat(obj[key]);
  if(temp>max){
    max=temp;
    keyName = key 
  }
}

console.log("Max value is:-" ,max, "
Property Name is :-", keyName)
另一答案

您可以获得一个结果或多个名称结果,请按照我的代码:

var obj_1= {Angry: "1.0", Fearful: "0.0", Happy: "0.0", Neutral: "0.0", Sad: "0.0"};
var obj_2 = {Angry: "1.0", Fearful: "1.0", Happy: "0.0", Neutral: "0.0", Sad: "0.0"};
//get only one name max
var result1 = Object.entries(obj_1).sort((a,b)=>(b[1]-a[1]));
console.log(result1[0][0]);

//get list of names max
var list_names = [];
var result2 = Object.entries(obj_2).sort((a,b)=>(b[1]-a[1]));
result2 = result2.filter(current=>{
    if(current[1]==result2[0][1]){
        list_names.push(current[0]);
        return current;
    }
})
// console.log(result2);
console.log(list_names);

以上是关于在对象中查找具有最大值的键的主要内容,如果未能解决你的问题,请参考以下文章

查找字典中最大 4 个值的键

在 Java Map 中查找与最大值关联的键

使用 Counter() 查找字典中的键

在用户定义的列表中查找具有最大字符数的类对象的项目

在字典中查找重复值并打印重复元素的键

从字典列表中查找值,其中dicts具有不同数量的键