0

For a given hash:

var hash = {
    a: "one",
    b: { cat: "two" }
};

Using two pipes || allowing to place an alternative value if one doesn't defined:

var number = hash.a || "just a number";  // -> "one"
var number = hash.c || "just a number";  // -> "just a number"

However, targeting the nested hash will result an error: Cannot read property 'value' of undefined:

var number = hash.c.dog || "just a number";  // -> Cannot read property 'value' of undefined

My question is how to target a nested hash and set a default value as we're doing with a 'plain' hash?

Lior Elrom
  • 19,660
  • 16
  • 80
  • 92
  • related: [Javascript: How to set object property given its string name](http://stackoverflow.com/q/13719593/218196), maybe this gives you an idea. – Felix Kling Mar 06 '14 at 02:28
  • @FelixKling Interesting... of course building a function for that task is possible however I wonder if there's a better way?! – Lior Elrom Mar 06 '14 at 02:35
  • Well, there is no built-in way if that's what you mean. If you want to test whether a nested property exists, you have to test the existence of every "intermediate" property as well. – Felix Kling Mar 06 '14 at 02:37
  • You're right. it is getting complicated as hash getting deeper. I'll give it more chance, maybe someone will come up with a creative idea. Thanks! – Lior Elrom Mar 06 '14 at 02:40

1 Answers1

1

JavaScript provides no special syntax for this. You need to test each potentially undefined value before assuming it's defined and trying to access one of its members.

You can still use || or && for this, but in a non-trivial case, it's probably better to just use an if.

Using ||:

var hash = {
    a: "one",
    b: { cat: "two" }
};

var x = (hash.c || {}).cat 

Using &&:

var x = hash && hash.c && hash.c.cat
user229044
  • 232,980
  • 40
  • 330
  • 338
  • You're probably right, JS doesn't have special syntax for those cases (as mention by Felix Kling as well). Thanks for the advise. – Lior Elrom Mar 06 '14 at 03:13