Created
July 17, 2012 20:54
-
-
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.
This file contains 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 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 |
This file contains 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
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