Convert string in Object or Array style notation to a reference
A Javascript function to convert a string in dotted and/or array notation into a reference.
e.g. "shallow[2].two[1][3].deepest"
HTML
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.10.0.css">
<script src="http://code.jquery.com/qunit/qunit-1.10.0.js"></script>
<h1 id="qunit-header">Unit Tests</h1>
<h2 id="qunit-banner"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-fixture"></div>
JavaScript
// 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) {
console.log(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");
...