-
-
Save samwolf1982/de113d495c7a3e629d9f54309e716684 to your computer and use it in GitHub Desktop.
Convert Javascript string in dot notation into an object reference
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
| // 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