在对象数组中查找具有“id”属性的最大值的对象 [英] Find object having maximum value for the `id` property in an array of objects
问题描述
在我的对象数组中,我想找到 id
属性值最高的对象。
In my array of objects, I want to find the object with the highest value for the id
property.
这是我的数组:
myArray = [
{
'id': '73',
'foo': 'bar'
},
{
'id': '45',
'foo': 'bar'
},
// …
];
通常我会使用 $。grep
来查找数组中的值,如下所示:
Generally I use $.grep
to find values in an array, like this:
var result = $.grep(myArray, function(e){
return e.id == 73;
});
但在这种情况下我需要提供一个特定的 id
我要选择的对象的值。
But in this case I need to provide a specific id
value for the object I want to select.
推荐答案
使用 map()数组的方法。使用map,您可以提供迭代数组中每个元素的函数。在该函数中,您可以计算出具有最高id的对象。例如:
Use the map() method of the array. Using map you can provide a function that iterates over every element in the array. In that function, you can work out the object with the highest id. For example:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
var maxid = 0;
myArray.map(function(obj){
if (obj.id > maxid) maxid = obj.id;
});
这将为您提供数组中对象的最大ID。
This will give you the max id of the objects in the array.
然后你可以用grep来获取相关的对象:
Then you can use grep to get the related object:
var maxObj = $.grep(myArray, function(e){ return e.id == maxid; });
或者,如果你只想要具有最大id的对象,你可以这样做:
Alternatively, if you just want the object with the max id, you can do this:
var maxid = 0;
var maxobj;
myArray.map(function(obj){
if (obj.id > maxid) maxobj = obj;
});
//maxobj stores the object with the max id.
这篇关于在对象数组中查找具有“id”属性的最大值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!