Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 using Elvis operator on object key with forward slash

I had problems with parsing, which is solved with Elvis operator, but if I have key that contains forward slash, I cant use Elvis operator because I have to put that key into square brackets.

Works if key is simple like this ( "firstname" )

{{ data?.record?.firstname }}

Does not work if key has forward brackets like this ( "name/first" )

{{ data?.record?['name/first']}}

It seems that Elvis is not available if I use square brackets.

Any workaround? Maybe a way to escape forward slash in . notation like this:

{{ data?.record?.name\\/first }}
like image 647
Milan Milanovic Avatar asked Mar 03 '16 09:03

Milan Milanovic


2 Answers

The Elvis operator is only available for the . not for other dereference operators like [].

As a workaround use

{{ data?.record ? data.record['name/first'] : null}}
like image 156
Günter Zöchbauer Avatar answered Oct 24 '22 08:10

Günter Zöchbauer


Actually, you can use both the ? and [] at the same time:

Sintaxe

obj?.prop
obj?.[expr]
arr?.[index]
func?.(args)

In your case, it should be:

{{ data?.record?.['name/first']}}

And still works if it's an array, like this:

attributes['bar/foo']?.[0]

Very useful... :-)

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

like image 29
Alex Gouvêa Vasconcelos Avatar answered Oct 24 '22 10:10

Alex Gouvêa Vasconcelos