Created
March 26, 2015 08:12
-
-
Save avin/98fd94c07f12cefb7c6d to your computer and use it in GitHub Desktop.
Object.byString
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
// 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