Skip to content

Instantly share code, notes, and snippets.

@markshust
Created January 20, 2016 21:55
Show Gist options
  • Select an option

  • Save markshust/8adf8303753a74d2105b to your computer and use it in GitHub Desktop.

Select an option

Save markshust/8adf8303753a74d2105b to your computer and use it in GitHub Desktop.
underscore mixin for something like lodash's _.get -- just use dot notation for arrays within objects, _.get(object, 'a.0.b.c');
_.mixin({
get: function (obj, key) {
var type = typeof key;
if(typeof obj === 'undefined' || type === 'undefined')
return undefined;
if (type == 'string' || type == "number") {
key = ("" + key).replace(/\[(.*?)\]/,/\[(.*?)\]/, function (m, key) { //handle case where [1] may occur
return '.' + key.replace(/["']/g,/["']/g, ""); //strip quotes
}).split('.');
}
for (var i = 0, l = key.length; i < l; i++) {
if (typeof obj !== 'undefined' && _.has(obj, key[i])) obj = obj[key[i]];
else return undefined;
}
return obj;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment