Skip to content

Instantly share code, notes, and snippets.

@soulwire
Created July 17, 2012 20:54
Show Gist options
  • Save soulwire/3132008 to your computer and use it in GitHub Desktop.
Save soulwire/3132008 to your computer and use it in GitHub Desktop.
Selects a property from an object based on a prioritised list and with an optional fallback.
var themeA = { name: 'Theme A', caption: { color: 'red' } };
var themeB = { name: 'Theme B', caption: { color: 'green' } };
var themeC = { name: 'Theme C', color: 'blue', caption: {} };
var themeD = { name: 'Theme D' };
// Test
var a = select( themeA, ['caption.color', 'color'], 'default' );
var b = select( themeB, ['caption.color', 'color'], 'default' );
var c = select( themeC, ['caption.color', 'color'], 'default' );
var d = select( themeD, ['caption.color', 'color'], 'default' );
var e = select( themeD, 'caption.color' );
console.log( a, b, c, d, e ); // red, green, blue, default, null
function select( target, options, fallback ) {
if ( typeof options === 'string' ) {
options = [ options ];
}
function search( prop ) {
var path = prop.split('.'), obj = target;
for ( var i = 0; i < path.length - 1; i++ ) {
obj = obj[ path[i] ];
if ( !obj ) return false;
}
return obj[ path[i] ];
}
for ( var i = 0; i < options.length; i++ ) {
var value = search( options[i] );
if ( value ) return value;
}
return fallback || null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment