Skip to content

Instantly share code, notes, and snippets.

@rtplv
Last active March 6, 2019 13:34
Show Gist options
  • Save rtplv/f24ce27a5297e5efb0a4e8ef2b24e729 to your computer and use it in GitHub Desktop.
Save rtplv/f24ce27a5297e5efb0a4e8ef2b24e729 to your computer and use it in GitHub Desktop.
Get object deep value by string key
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