'RxJS: Removing fields from an object

Lets say I have an object with 4 fields like this:

obj = {a:"3", b:"7", c:"10", d:"123"}

and I need to 'narrow' it to an object with fewer fields, like that:

newObj = {a:"3", c:"10"}

I know this can be done by deleting the fields (ie. delete obj.b )

My question is, can this be done with RxJS? And if yes, how???

Thanks a lot!



Solution 1:[1]

You if you have an Observable, that emits the shape above, you can do something like this:

Rx.Observable.of({ a:"3", b:"7", c:"10", d:"123" })
  .map(({ a, c }) => ({ a, c }))

In the mapping function I destructure the object, then create an object literal with the shorthand syntax. Mind that these are es6/7 features.

But you really don't need rxjs or Observables to do this:

const original = { a:"3", b:"7", c:"10", d:"123" }
const changed = { a: original.a, c: original.c }

Solution 2:[2]

If you want to remove specific fields from the object (or stream of objects), rather than keeping specific ones, then you can use the following operator:

const removeFieldsOp = (props)=>obs=>obs.pipe(map(({...o})=>
(props.forEach(prop=>delete o[prop]), o)));

of({ a:"3", b:"7", c:"10", d:"123" }).pipe(removeFieldsOp(['b','d']))
.subscribe(console.log);

//{ a: '3', c: '10' }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Balázs Édes
Solution 2 Marinos An