从对象获取具有最高价值的密钥 [英] Getting key with the highest value from object

查看:73
本文介绍了从对象获取具有最高价值的密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的物体:

I have a object like that one:

Object {a: 1, b: 2, undefined: 1} 

如何快速从中提取最大值标识符(此处为b)?我尝试将其转换为数组然后进行排序,但没有成功,因为它是按字母顺序进行排序的(为了获得三个值中的一个值,来回处理数据似乎是一种过大的杀伤力.)

How can I quickly pull the largest value identifier (here: b) from it? I tried converting it to array and then sorting, but it didn't work out, since it got sorted alphabetically (and it seems like a overkill to juggle data back and forth just for getting one value out of three).

推荐答案

例如:

var obj = {a: 1, b: 2, undefined: 1};

Object.keys(obj).reduce(function(a, b){ return obj[a] > obj[b] ? a : b });

ES6 中:

var obj = {a: 1, b: 2, undefined: 1};

Object.keys(obj).reduce((a, b) => obj[a] > obj[b] ? a : b);

这篇关于从对象获取具有最高价值的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆