如何在特定对象值为最大值的数组中查找对象
How to find the object in an array where particular object value is max
嗨 下面是 JSON 对象数组
[
{
"BookingId": 366024,
"BookingDetailId": 340708,
"JobCode" : 13
},
{
"BookingId": 366023,
"BookingDetailId": 340707,
"JobCode" : 12
},
{
"BookingId": 366022,
"BookingDetailId": 340706,
"JobCode" : 12
}
]
我想获取特定的数组对象,其中 BookingId 为 Max,而 JobCode 为 12,例如。在上面的数组中我想要对象{
"BookingId": 366023,
"BookingDetailId": 340707,
"JobCode" : 12
} BookingId为max,JobCode为12.
如何在 angular 6
尝试过代码
var a = this.GridSource.find(x => x.JobCode == 12 &&
x.BookingId == Math.max.apply(Math, this.GridSource.map
(function(o) { return o.BookingId; })));
您可以为此使用reduce。我在下面做了一个例子,希望这会有所帮助。如果没有满足条件的项目,则 reduce 的结果将是 null
此外,不要忘记类型:)
interface GridItem {
BookingId: number;
BookingDetailId: number;
JobCode: number;
}
const GridSource: GridItem[] = [
{
BookingId: 366024,
BookingDetailId: 340708,
JobCode: 13
},
{
BookingId: 366023,
BookingDetailId: 340707,
JobCode: 12
},
{
BookingId: 366022,
BookingDetailId: 340706,
JobCode: 12
}
];
const foundGridItem: GridItem = GridSource.reduce(
(result: GridItem, value: GridItem) =>
value.JobCode === 12 &&
(result === null || value.BookingId > result.BookingId)
? value
: result,
null
);
你可以利用reduce找到最大元素,然后在find中使用它。
var max = array.reduce(function(prev, curr) {
return prev['BookingId'] > curr['BookingId'] ? prev : curr;
});
var elem = array.find(x => x['JobCode'] == 12 && x['BookingId'] == max['BookingId']);
嗨 下面是 JSON 对象数组
[
{
"BookingId": 366024,
"BookingDetailId": 340708,
"JobCode" : 13
},
{
"BookingId": 366023,
"BookingDetailId": 340707,
"JobCode" : 12
},
{
"BookingId": 366022,
"BookingDetailId": 340706,
"JobCode" : 12
}
]
我想获取特定的数组对象,其中 BookingId 为 Max,而 JobCode 为 12,例如。在上面的数组中我想要对象{ "BookingId": 366023, "BookingDetailId": 340707, "JobCode" : 12 } BookingId为max,JobCode为12.
如何在 angular 6
尝试过代码
var a = this.GridSource.find(x => x.JobCode == 12 &&
x.BookingId == Math.max.apply(Math, this.GridSource.map
(function(o) { return o.BookingId; })));
您可以为此使用reduce。我在下面做了一个例子,希望这会有所帮助。如果没有满足条件的项目,则 reduce 的结果将是 null
此外,不要忘记类型:)
interface GridItem {
BookingId: number;
BookingDetailId: number;
JobCode: number;
}
const GridSource: GridItem[] = [
{
BookingId: 366024,
BookingDetailId: 340708,
JobCode: 13
},
{
BookingId: 366023,
BookingDetailId: 340707,
JobCode: 12
},
{
BookingId: 366022,
BookingDetailId: 340706,
JobCode: 12
}
];
const foundGridItem: GridItem = GridSource.reduce(
(result: GridItem, value: GridItem) =>
value.JobCode === 12 &&
(result === null || value.BookingId > result.BookingId)
? value
: result,
null
);
你可以利用reduce找到最大元素,然后在find中使用它。
var max = array.reduce(function(prev, curr) {
return prev['BookingId'] > curr['BookingId'] ? prev : curr;
});
var elem = array.find(x => x['JobCode'] == 12 && x['BookingId'] == max['BookingId']);