0

I have an observable

someObjs$ = this.getData().pipe(
    map((data: Data) => ({
        a: true,
        b: true,
        c: true,
      })
    ),

If a flag a user has set somewhere is false, I want to always return to true for a key even if that key doesn't exist once the Observable is unwrapped in the template.

Example,

someObj$ | async as obj

{{ obj['d'] }} // true
filipbarak
  • 1,835
  • 2
  • 17
  • 28
  • Not possible without Proxy. JavaScript objects don't have a fallback "all other properties" accessor. https://stackoverflow.com/questions/1529496/is-there-a-javascript-equivalent-of-pythons-getattr-method – ggradnig Feb 12 '19 at 15:44

1 Answers1

0

I'm not sure if you want any key (obj['foo'],obj['bar']) or predefined keys obj['d'] but I assume predefined keys.

You can use startWith operator within the pipe method. Create a new Data instance and assign d property with spread (...) operator.

const newData = new Data();

someObjs$ = this.getData().pipe(
    startWith({...newData, d: true}),
    map((data: Data) => ({
        a: true,
        b: true,
        c: true,
      })
 )

Or in Data class, you can assign default values. Then you won't need spread operator. You could just use startWith with a default Data instance.

Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
  • I'm unfortunately looking for a solution for any given key. – filipbarak Feb 12 '19 at 15:34
  • Why do you want such feature? Maybe I can help further if I know the purpose. And maybe you can check if the property exists like "{{ obj['foo'] ? obj['foo'] : DEFAULT_VALUE }}" – Harun Yilmaz Feb 12 '19 at 15:52