Rewriting clumsy code that gets the value of a nested property in JS object I have an API that returns JSON, where the value that I need is stored in either one of the two object properties: 

data.d.GetContextWebInformation.FormDigestValue


or 

data.value.GetContextWebInformation.FormDigestValue


The code that I'm using is pretty clumsy. At first, I used something like this: 

if (data &amp;&amp; data.d &amp;&amp; data.d.GetContextWebInformation &amp;&amp; data.d.GetContextWebInformation.FormDigestValue) {
    this.options.token = data.d.GetContextWebInformation.FormDigestValue;
} else {
// check for second one


Now I've rewritten it using try/catch, and it looks a bit cleaner, but still clumsy: 

    var token; 
    try {
        // If Verbosity was odata=verbose:
        token = data.d.GetContextWebInformation.FormDigestValue;
    } catch (ex) {
        try {
            // If Verbosity was odata=nometadata or odata=minimalmetadata:
            token = data.value.GetContextWebInformation.FormDigestValue;
        } catch (ex) {
            throw 'Unable to obtain authorization token.';
        }
    } finally {
        if (token) { this.options.token = token; }
    }


What would be a better way to write the same code for a cleaner, nicer look? If that matters, I need to support IE9 so probably can't use newer language features.
If you're certain the token exists in either of the objects you can do: 

First check for the existence of the value in data. 

var value = data.d || data.value;


then access the value to get the token

var token = value &amp;&amp; value.GetContextWebInformation.FormDigestValue;




var value = data.d || data.value;

var token = value &amp;&amp; value.GetContextWebInformation.FormDigestValue;


if (token) {
  this.options.token = token;
}




Otherwise, you can use getIn function:



function getIn(pathArray, obj) {
  var tmp = obj;
  for (var i = 0; i &lt; pathArray.length; i++) {
    if (tmp.hasOwnProperty(pathArray[i])) {
      tmp = tmp[pathArray[i]];
      continue;
    }
    return undefined;
  }
  return tmp;
}

var token = getIn(['d', 'GetContextWebInformation', 'FormDigestValue'], data) ||
            getIn(['value', 'GetContextWebInformation', 'FormDigestValue'], data);

if (token) {
  this.options.token = token;
}