javascript 下划线找到对象值的最小值和最大值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15851369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:19:18  来源:igfitidea点击:

underscore to find min and max of object value

javascriptunderscore.js

提问by bsr

As per the tutorial here,

根据这里的教程,

A collection can either be an array or an object, an associate array in JavaScript

集合可以是数组或对象,JavaScript 中的关联数组

does that mean all the functions under collectionis equally applicable to object literals. For example, I wanted to pick the values based on a condition. Say,

这是否意味着下面的所有函数collection都同样适用于对象文字。例如,我想根据条件选择值。说,

var obj = {
"1": {id: 1, val: 2},
"2": {id: 2, val: 5},
"3": {id: 3, val: 8},
"4": {id: 4, val: 1}
}

I want to find max and min of val field. Looking at the API, I was thinking to use pluckto get an array of val, then do minand max.

我想找到 val 字段的最大值和最小值。看着 API,我想用它pluck来获取一个数组val,然后做minmax

  • can I apply pluck to object (as the api example show the use in an array of objects)
  • is there a better way?
  • 我可以将 pluck 应用于对象吗(如 api 示例显示在对象数组中的使用)
  • 有没有更好的办法?

Thanks.

谢谢。

回答by Bergi

does that mean all the functions under collection is equally applicable to object literals?

这是否意味着集合下的所有函数都同样适用于对象文字?

Yes.

是的

can I apply pluck to object (as the api example show the use in an array of objects)

我可以将 pluck 应用于对象吗(如 api 示例显示在对象数组中的使用)

Have you tried it? Yes, you can, but you will get back an array.

你试过吗?是的,你可以,但你会得到一个数组。

is there a better way?

有没有更好的办法?

Math.min.apply(null, _.pluck(obj, "val"))(or _.min(_.pluck(obj, "val"))) for getting the minimum valueis fine. Yet, if you wanted to get the whole object (with id) you might also use the iteratorparameterof min/max:

Math.min.apply(null, _.pluck(obj, "val"))(或_.min(_.pluck(obj, "val")))为获得最低是好的。但是,如果您想获取整个对象(带有 id),您还可以使用min/maxiterator参数

var lowest = _.min(obj, function(o){return o.val;});

回答by Matt Fletcher

Another way of doing this, and great if you want to return multiple rows that all have a high value, is as such:

这样做的另一种方法,如果你想返回多行都具有高值,很好,是这样的:

_.where(obj, {score: _.max(_.pluck(obj, 'value'))});

回答by Jerad

No need to be fancy. Just create an array of the target values with the mapfunction and use _minto find the minimum value.

没必要花哨。只需使用该map函数创建一个目标值数组并用于_min查找最小值。

Standard

标准

var minimum = _.min(data.map(function(rec) {return rec.val}))

ES6

ES6

let minimum = _.min(data.map((rec) => {return rec.val}))