Remove part of an object on the rxjs way

Viewed 125

I have the following object:

const myObject = {
  items:[
    {
      name: 'John',
      age: 35,
      children: [
        {
          child: 'Eric',
          age: 10,
          sex: 'M'
        },
        {
          child: 'Andrea',
          age: 4,
          sex: 'F'
        }
      ]
    },
    {
      name: 'Bob',
      age: 23,
      children: [
        {
          child: 'Oscar',
          age: 1,
          sex: 'M'
        }
      ]
    }
  ]
}

And I filter the results by adding this:

const source = of(myObject).pipe(
  map(x => x.items),
  map(x => {
    return x.filter(y => {
      return y.children.find(y => y.sex === 'M');
    })
  })
);

source.subscribe(x => console.log(x));

The filter by sex does work except I want to remove the female children from the json. In this case Andrea should been removes from the object.

Perhaps I'm missing the knowledge about another operator that I can use ?

1 Answers

You need to filter it too.

const source = of(myObject).pipe(
  map(x => x.items),
  map(x => {
    return x.filter(y => {
      return y.children.some(y => y.sex === 'M');
    });
  }),
  map(x => {
    return x.map(y => {
      return {
        ...y,
        children: y.children.filter(c => c.sex === 'M');
      };
    });
  }),
);

source.subscribe(x => console.log(x));
Related