简体   繁体   English

如何使用最大算子 RxJs

[英]How to use Max operator RxJs

I am trying to get the max startDate on a nested object.我正在尝试在嵌套的 object 上获得最大 startDate。 Is there a way to use a max function in RxJs for nested items to get the lastest date?有没有办法在 RxJs 中使用最大 function 来获取最新日期?

JSON response body JSON 响应体

const fakeData = [
{
  Name: "Blue",
  Attributes: {
    projex: [
      {
        dateStart: "2020-04-12T00:00:00",
        Project: "50",
        HeightPay: "1"
      },
      {
        dateStart: "2020-03-05T00:00:00",
        Project: "50",
      },
      {
        dateStart: "2020-02-04T00:00:00",
        Project: "50",
      }
    ]
  }
}

Desired OutPut所需 OutPut

 const fakeData = [
{
  Name: "Blue",
  Attributes: {
    projex: [
      {
        dateStart: "2020-04-12T00:00:00",
        Project: "50",
        HeightPay: "1"
      }
    ]
  }
}

Code代码

  const sort = fakeData.map(data => ({
  ...data,
  Attributes: {
    projex: max((a, b) => a.Attributes.dateStart < b.AttributesdateStart ? -1 : 1)
  }

}))

If this was your component this is what you could do如果这是您的组件,这就是您可以做的

import { Component, OnInit } from '@angular/core';
import { of } from 'rxjs';
import { max, map, mergeMap } from 'rxjs/operators';

@Component({
  selector: 'hello',
  template: `<h1>Hello</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})

export class HelloComponent implements OnInit  {

  fakeData = [
    {
      Name: "Blue",
      Attributes: {
        projex: [
          {
            dateStart: "2020-04-12T00:00:00",
            Project: "50",
            HeightPay: "1"
          },
          {
            dateStart: "2020-03-05T00:00:00",
            Project: "50",
          },
          {
            dateStart: "2020-02-04T00:00:00",
            Project: "50",
          }
        ]
      }
    },
    {
      Name: "Red",
      Attributes: {
        projex: [
          {
            dateStart: "2020-04-13T00:00:00",
            Project: "50",
            HeightPay: "1"
          },
          {
            dateStart: "2020-03-05T00:00:00",
            Project: "50",
          },
          {
            dateStart: "2020-02-04T00:00:00",
            Project: "50",
          }
        ]
      }
    }
  ];

  fakeObservable$ = of(...this.fakeData);

  ngOnInit() {
    this.fakeObservable$.pipe(
    mergeMap(x => x.Attributes.projex),
    max((a, b) => new Date(a.dateStart) < new Date(b.dateStart) ? -1 : 1 ))
    .subscribe(latest => {
      var res = this.fakeData.find(x => x.Attributes.projex.find(z => z.dateStart === latest.dateStart));
      console.log(res);
    })
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM