Last active
December 11, 2015 20:48
-
-
Save dreadjr/4657736 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var obj = { | |
levelOne: { | |
levelTwo: { | |
property: 'Got me!' | |
}, | |
levelOneArray: [1,2,3] | |
} | |
} | |
function run(obj) { | |
// Approach #1 | |
if (obj) { | |
var levelOne = obj.levelOne; | |
if (levelOne) { | |
var levelTwo = levelOne.levelTwo; | |
if (levelTwo) { | |
var propertyValueOrUndefined = levelTwo.property; | |
if (propertyValueOrUndefined) | |
console.log(propertyValueOrUndefined); | |
} | |
var levelOneArray = levelOne.levelOneArray; | |
if (levelOneArray && levelOneArray.length) { | |
console.log(levelOneArray[0]); | |
} | |
} | |
} | |
// Approach #2 | |
var propertyValueOrUndefined = (((obj||{}).levelOne||{}).levelTwo||{}).property; | |
console.log(propertyValueOrUndefined); | |
var levelOneArrayElementOneOrUndefined = (((obj||{}).levelOne||{}).levelOneArray||[])[0]; | |
console.log(levelOneArrayElementOneOrUndefined); | |
} | |
// run some queries | |
run(obj); | |
run(null); | |
run(undefined); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment