Skip to content

Instantly share code, notes, and snippets.

@avin
Created March 26, 2015 08:12
Show Gist options
  • Save avin/98fd94c07f12cefb7c6d to your computer and use it in GitHub Desktop.
Save avin/98fd94c07f12cefb7c6d to your computer and use it in GitHub Desktop.
Object.byString
// Usage: Object.byString(someObj, 'part3[0].name');
// Demo: http://jsfiddle.net/alnitak/hEsys/
Object.byString = function(o, s) {
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var n = a[i];
if (n in o) {
o = o[n];
} else {
return;
}
}
return o;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment