// By Scott Donnelly, MIT Licensed.
// Based on the answer to the StackOverflow question
// "Convert string in dot notation to reference" by ninjagecko
// http://stackoverflow.com/a/6394168/642703
// added empty string handling and array notation handling.
// I use this with AngularJS, to resolve references passed to
// a directive via an HTML attribute.
// This does not handle nested references - there is no way to resolve the nested
// variable references without using eval(),
// as described here http://stackoverflow.com/questions/598878
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);
};
// Test object style references
test("function string_to_ref", 8, function() {
var obj_1 = ["zero", [ "deep-zero", "deep-one", "deep-two" ], {two: "two"}, "three" ];
var obj_2 = {
inner: { deeper: { deepest: "got it!" } },
shallow: [
{ zero: "shallow zero"},
{ one: "shallow one" },
{
two: [
"deep zero", [
"deeper zero",
"deeper one",
"deeper two", {
deep: {deepest : "It Works!" }
}
]
]
}
]
};
strictEqual(string_to_ref(obj_2, ""), obj_2, "Empty string");
strictEqual(string_to_ref(obj_2, "shallow"), obj_2.shallow, "Single string");
strictEqual(string_to_ref(obj_2, "inner.deeper.deepest"), obj_2.inner.deeper.deepest, "Multiple dotted");
strictEqual(string_to_ref(obj_1, "[1]"), obj_1[1], "Single array");
strictEqual(string_to_ref(obj_1, "[1][2]"), obj_1[1][2], "Multiple array");
strictEqual(string_to_ref(obj_2, "shallow[2]"), obj_2.shallow[2], "string then array");
strictEqual(string_to_ref(obj_1, "[2].two"), obj_1[2].two, "array then string");
strictEqual(string_to_ref(obj_2, "shallow[2].two[1][3].deep.deepest"), obj_2.shallow[2].two[1][3].deep.deepest, "Super Power Combo");
});
<h1 id="qunit-header">Unit Tests</h1>
<h2 id="qunit-banner"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-fixture"></div>
External resources loaded into this fiddle: