Skip to content

Instantly share code, notes, and snippets.

@matiaslopezd
Last active June 14, 2021 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matiaslopezd/baaa773957aab3301bc3281063989732 to your computer and use it in GitHub Desktop.
Save matiaslopezd/baaa773957aab3301bc3281063989732 to your computer and use it in GitHub Desktop.
Deep object access by string path
// This function can be used on frontend. For better performance use the "for" version
Object.byString = function(object, string) {
string = string.replace(/\[(\w+)]/g, '.$1'); // convert indexes to properties
string = string.replace(/^\./, ''); // strip a leading dot
const array = string.split('.');
array.forEach((key) => {
if (key in object) object = object[key];
});
return object;
}
// Better performance, suggested to use in node
Object.byString = function(object, string) {
string = string.replace(/\[(\w+)]/g, '.$1'); // convert indexes to properties
string = string.replace(/^\./, ''); // strip a leading dot
const array = string.split('.');
for (let index = 0, limit = array.length; index < limit; ++index) {
const key = array[index];
if (key in object) {
object = object[key];
} else {
return;
}
}
return object;
}
@matiaslopezd
Copy link
Author

Difference of performance here: https://jsbench.me/p6kpx0bqgh/1

@matiaslopezd
Copy link
Author

Thanks to Alnitak, to post the solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment