最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular2 using Elvis operator on object key with forward slash - Stack Overflow

programmeradmin3浏览0评论

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 }}

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 }}
Share Improve this question asked Mar 3, 2016 at 9:56 Milan MilanovicMilan Milanovic 4331 gold badge7 silver badges14 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 14

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}}

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/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

发布评论

评论列表(0)

  1. 暂无评论