JSFiddle - React, Tailwind, and code Playground
JavaScript
// We have a complex object with lots of properties
// Clearer test object copied from @iancmcc
var testObject = {
a: {
b: {
c: 1
}
}
};
// We want to be able to test for properties where any step in the property chain
// may or may not exist
// This results in an error:
/*
if ( testObject.a.x.c ) {
console.log( true );
} else {
console.log( false );
}
*/
///////////////////////////////////////////////////////////////
// OPTION #1 //
///////////////////////////////////////////////////////////////
// This pattern works, but is obnoxiously repetitive
if ( testObject && testObject.a && testObject.a.b && testObject.a.b.c ) {
console.log( '&&, a.b.c:', true );
} else {
console.log( '&&, a.b.c:', false );
}
if ( testObject && testObject.a && testObject.a.x && testObject.a.b.c ) {
console.log( '&&, a.x.c:', true );
} else {
console.log( '&&, a.x.c:', false );
}
///////////////////////////////////////////////////////////////
// OPTION #2 //
///////////////////////////////////////////////////////////////
// This pattern is suggested by @iancmcc
if ( ((( testObject || {} ).a || {} ).b || {} ).c ) {
console.log( '@iancmcc, a.b.c:', true );
} else {
console.log( '@iancmcc, a.b.c:', false );
}
if ( ((( testObject || {} ).a || {} ).x || {} ).c ) {
console.log( '@iancmcc, a.x.c:', true );
} else {
console.log( '@iancmcc, a.x.c:', false );
}
///////////////////////////////////////////////////////////////
// OPTION #3 //
///////////////////////////////////////////////////////////////
// Function suggested by @iancmcc
// http://pastebin.ca/2145691
// reformatted according to my largely arbitrary preferences
function getProperty( object, propertiesString ) {
var split = propertiesString.split( '.' );
for ( var i = 0, length = split.length; i <...