1

I have a data structure like the following being returned as an observable using Akita state management, but in essence its just like any other observable, if there is some way to do this in Akita even better but any pointers with rxjs would be great also.

    {
        title: "Cool project",
        date: "12-09-2020 15:10:33"
        events: [{
            id: 1,
            title: "Beer festival",
            location: "Paris"
        },{
            id: 2,
            title: "Fashion week",
            location: "Dubai"
        }]
    }
    
    

I would like to perform some kind of filtering on the subarray of events and return the following as an observable also where I just have the event I need having filtered by the ID but also to return the top level object properties like date etc

    {
        title: "Cool project",
        date: "12-09-2020 15:10:33"
        event: {
            id: 1,
            title: "Beer festival",
            location: "Paris"
        }
    }        
Kravitz
  • 2,769
  • 6
  • 26
  • 53
  • You shouldn't change the object and affect it's integrety in my opinion. Maybe you could explain why you need to do this. If it's only for display, you could use a filter on this array when you're about to display. – Leccho Oct 27 '20 at 17:20

2 Answers2

1

Do you mean something like this? Of course you should adapt the id filter.

    of({
  title: "Cool project",
  date: "12-09-2020 15:10:33",
  events: [{
    id: 1,
    title: "Beer festival",
    location: "Paris"
  }, {
    id: 2,
    title: "Fashion week",
    location: "Dubai"
  }]
}
).pipe(map((val) => {
  const val2: any = {};
  val2.title = val.title;
  val2.date = val.date;
  val2.event = val.events.find((e) => e.id === 1)
  return val2
})).subscribe((res) => console.log(res));
0

    import { of } from "rxjs";
    import { filter, map } from "rxjs/operators";
    
    const sample = {
      title: "Cool project",
      date: "12-09-2020 15:10:33",
      events: [
        {
          id: 1,
          title: "Beer festival",
          location: "Paris"
        },
        {
          id: 2,
          title: "Fashion week",
          location: "Dubai"
        }
      ]
    };
    
    const idToFilter = 1;
    const source = of(sample).pipe(
      map(res => {
        const subArrayElement = res.events.find(event => event.id === idToFilter);
        return {
          title: res.title,
          date: res.date,
          event: subArrayElement
        };
      })
    );
    
    source.subscribe(console.log);

See the working example here: example

Owen Kelvin
  • 14,054
  • 10
  • 41
  • 74
evantha
  • 54
  • 6