Last active
April 9, 2024 16:23
-
-
Save brianmriley/ba8cbaaa7c7e49ddf1d1 to your computer and use it in GitHub Desktop.
Convert Javascript string in dot notation into an object reference
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
// pulled from SO http://stackoverflow.com/questions/6393943/convert-javascript-string-in-dot-notation-into-an-object-reference | |
// NOTE: Array.reduce() may not be available in older browsers | |
function index(obj,i) {return obj[i]} | |
'a.b.etc'.split('.').reduce(index, obj); | |
var obj = {a:{b:{etc:5}}}; | |
index(obj,'a.b.etc'); | |
index(obj,['a','b','etc']); // works with both strings and lists | |
index(obj,'a.b.etc', 123); // setter-mode - third argument (possibly poor form) | |
index(obj,'a.b.etc'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment