0
var foo = a.foo or {}
var bar = foo.bar or {}

It is tedious to do this for every level of nesting.

Can I somehow do instead?

var bar = a.foo.bar or {}
eugene
  • 36,347
  • 56
  • 224
  • 435
  • No, not really, since otherwise you would get property bar doesn't exist on undefined, you could however make a function that checks this – Icepickle Oct 14 '16 at 09:16
  • You could do it with a small utility function as well (though I also believe Nina's code to be the easiest), like such: https://jsfiddle.net/Icepickle/85cbq9h1/ – Icepickle Oct 14 '16 at 09:26

2 Answers2

2

You need a nested approach, you may have a look to logical operators and objects.

var bar = a && a.foo && a.foo.bar || {};
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
0

In javascript you need to use || to indicate for or.

var bar = a.foo.bar || {}; // However, a, a.foo may also be undefined

So, you need to check them using && operator to know if they all are defined:

var bar = a && a.foo && a.foo.bar || {};
Bhojendra Rauniyar
  • 78,842
  • 31
  • 152
  • 211