builder_247 builder_247 -4 years ago 69
Node.js Question

How to default to a value on non-existing json value in javascript?

My node.js application uses numerous json values from an API. For example:


What I want to know is how would I default to a value of 0 when calling a json path that doesn't exist? If I do
var coins = + player.game2.coins;
and the player has no coins in game2, I would get TypeError: Cannot read property 'coins' of undefined, since the API doesn't have the object there.

Answer Source

You can use logical operators && and || to accomplish this.

var coins = +
  ((player.game2 && player.game2.coins) || 0);

If player may be undefined then you will need to check to ensure that exists before checking game2. So it'd be ((player && player.game2 && player.game2.coins) || 0)

It makes sense once you realize how the code is evaluated. && is the AND operation and so it checks that each value exists from left to right. player exists AND player.game2 exists AND player.game2.coins exists and thus stops the comparison and the value is used. If either of those fail then it goes outside the parenthesis and does the OR which returns 0 for a default value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download