Scott Donnelly

Javascript function to convert a string in dot and/or array notation into a reference

I needed to convert a string into an object reference. Over on StackOverflow, ninjagecko had created a beautiful function to resolve dotted string references, but I needed to handle array style references as well as dotted ones. Here is my resulting function, I hope it can be of use to someone else!

string_to_ref = function (object, reference) {
    function arr_deref(o, ref, i) {
        return !ref ? o : (o[ref.slice(0, i ? -1 : ref.length)]);
    function dot_deref(o, ref) {
        return !ref ? o : ref.split('[').reduce(arr_deref, o);
    return reference.split('.').reduce(dot_deref, object);

now I can use my typeahead tag directive for AngularJS, and pass through the model in an attribute, even if it is a reference deep into an object, like so:

Before you ask, no, it can’t handle nested variables, such as something like this:

This is not possible without using evil eval, since it is not possible to get a reference to the closure containing current_persona. I suppose I could make a version that would work with references to global variables only, but you shouldn’t be polluting the global namespace. Besides, the same can be acheived by a bit of string concatenation and AngularJS’ { { } } operators.

I’ve created a JSFiddle so you can, well, fiddle with the JS. It contains some unit tests using QUnit so that you can check it works.