Last active
June 14, 2021 19:30
-
-
Save matiaslopezd/baaa773957aab3301bc3281063989732 to your computer and use it in GitHub Desktop.
Deep object access by string path
This file contains hidden or 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
// 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; | |
} |
This file contains hidden or 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
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Difference of performance here: https://jsbench.me/p6kpx0bqgh/1