![](/img/trans.png)
[英]return key value pair from object whose key matches certain condition with javascript and underscore
[英]Javascript, Underscore trying to return the key of an object with the highest value
我有一個對象
obj = { "13-17": { "total_fans": 5 },
"18-24": { "total_fans": 10 },
"25-34": { "total_fans": 15 }
}
並且我想從obj
返回具有最高total_fans
的對象的鍵,因此在這種情況下它將是25-34
結合_.keys和_.max怎么樣?
_.max(_.keys(obj), function(key){
return obj[key]["total_fans"];
});
這將返回“ 25-34”
小心空對象({}),它將返回-Infinity ...之前使用_.isEmpty(obj)進行測試!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.