The wonders of emily.js: getNestedProperty and setNestedProperty
Emily.js (https://github.com/flams/emily) has a great bunch of modules to allow you build scalable and fast applications, but it also has some hidden gems that happen to be very useful, solving common problems that we usually overlook and work around with an ad-hoc solution.
Today's hidden gems are Tools.getNestedProperty and Tools.setNestedProperty.
Let's say that we have an object with the following structure:
var foo = { bar: { baz: "value" } };
And we want to test baz. If we aren't sure if foo even has a bar object, we usually do something like:
if (foo.bar && foo.bar.baz == "value") { ... }
This becomes even more complex as the property that we want to access is nested deeper into the structure. But with getNestedProperty from emily.Tools, we have a nicer way to access it:
var Tools = require("emily").Tools; // getNestedProperty will return the value corresponding to a path, defined via a simple string if (Tools.getNestedProperty(foo, "bar.baz") == "value") { ... }
If bar weren't set, or if we try accessing another property, we'll just get undefined in return
typeof Tools.getNestedProperty(foo, "qux.baz") == "undefined"; // true
Also, if no path is given, the value is directly returned
Tools.getNestedProperty(foo) === foo; // true
Even better, if we now wanted to set a property that is deeply nested in the structure, but we don't want to go through the incremental creation of nested objects:
// We want foo.qux.baz to equal "value" foo.qux = foo.qux || {}; foo.qux.baz = "value";
We can use Tools.setNestedProperty to simplify the previous:
Tools.setNestedProperty(foo, "qux.baz", "value"); foo.qux.baz; // "value";
Also, if the object is actually an array:
var foo = []; Tools.setNestedProperty(foo, "100.qux.baz", "value"); foo[100].qux.baz; // "value";
These tools were added to Emily.js to help Olives.js' data-binding, so you can declare an object's nested property to bind with a function or the property of a DOM element.









