Last active
March 6, 2019 13:34
-
-
Save rtplv/f24ce27a5297e5efb0a4e8ef2b24e729 to your computer and use it in GitHub Desktop.
Get object deep value by string key
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
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) { | |
const k = a[i]; | |
if (k in o) { | |
o = o[k]; | |
} else { | |
return; | |
} | |
} | |
return o; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment