【问题标题】:How to find the object in an array where particular object value is max如何在特定对象值为最大值的数组中查找对象
【发布时间】:2020-02-19 22:14:12
【问题描述】:

嗨,下面是对象的 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, “工作代码”:12 },其 BookingId 最大,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; })));

【问题讨论】:

    标签: json angular angular6 angular5


    【解决方案1】:

    您可以为此使用 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
    );
    

    【讨论】:

      【解决方案2】:

      你可以利用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']);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-15
        • 1970-01-01
        • 2022-07-08
        相关资源
        最近更新 更多