Skip to content

Instantly share code, notes, and snippets.

@lstebner
Created August 31, 2012 23:41
Show Gist options
  • Save lstebner/3561193 to your computer and use it in GitHub Desktop.
Save lstebner/3561193 to your computer and use it in GitHub Desktop.
Underscore mixin get object property with default value
//get a key from an object if it exists, otherwise use default
_.mixin({
get: function(obj, key, default_val){
if (obj && _.has(obj, key)){
return obj[key];
}
else{
return default_val != undefined ? default_val : '';
}
}
});
@lstebner
Copy link
Author

updated to make sure obj exists before calling _.has to preview an error when obj is null

@lstebner
Copy link
Author

updated to check for default_val to not be undefined because it was returning an empty string when default_val was set to false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment