Skip to content

Instantly share code, notes, and snippets.

@shmaltorhbooks
Created September 14, 2015 08:54
Show Gist options
  • Select an option

  • Save shmaltorhbooks/7de9a976ca248d5cdfcd to your computer and use it in GitHub Desktop.

Select an option

Save shmaltorhbooks/7de9a976ca248d5cdfcd to your computer and use it in GitHub Desktop.
access to object properties by string path
Object.path = Object.byString = function(obj, str, undefined) {
if (str in obj) {
return obj[str];
}
if ((!str.length) || (null === obj)) {
return obj;
}
var a = str.replace(/\[(\w+)\]/g, '.$1').replace(/^\./, '').split('.'); // convert indexes to properties and strip a leading dot
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if ((null !== obj) && (k in obj)) {
obj = obj[k];
} else {
return undefined;
}
}
return obj;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment