Checking sanity of a JSON object

Viewed 1090

Time and again I have to deal with code like consider following hypothetical example:

if (node.data.creatures.humans.women.number === Infinity) {
  // do-someting
}

Now, problem is that if node is undefined this condition will break. Similarly, it will break if node.data is undefined, node.data.creatures is undefined and so on.

So I end up using following kind of long condition:

if (node && node.data && node.data.creatures && node.data.creatures.humans && node.data.creatures.women && node.data.creatures.humans.women.number === Infinity) {
  // do-someting
}

Now, imagine I have to use parts of that JSON object in many other parts of code too.

The code suddenly starts looking very ugly. Is there a better way of avoiding errors like "Cannot call property of undefined" kind of errors due to the first condition I mentioned such that the code looks better too.

How do you deal with such situations?

3 Answers
Related