Skip to content

Instantly share code, notes, and snippets.

@brianmriley
Last active April 9, 2024 16:23
Show Gist options
  • Save brianmriley/ba8cbaaa7c7e49ddf1d1 to your computer and use it in GitHub Desktop.
Save brianmriley/ba8cbaaa7c7e49ddf1d1 to your computer and use it in GitHub Desktop.
Convert Javascript string in dot notation into an object reference
// 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