简体   繁体   中英

How to use Max operator RxJs

I am trying to get the max startDate on a nested object. Is there a way to use a max function in RxJs for nested items to get the lastest date?

JSON response body

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

 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);
    })
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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