Skip to content

Instantly share code, notes, and snippets.

@DimitrK
Created May 25, 2013 13:25
Show Gist options
  • Save DimitrK/5649029 to your computer and use it in GitHub Desktop.
Save DimitrK/5649029 to your computer and use it in GitHub Desktop.
This gist is used to augment object instances with a function called expand. It checks if the object has some property which includes dot characters in its name and translates it to deep level property nesting. e.g: account['user.name'] ==> account.user.name
// Transforms a property of object which includes dots to nested property as follows
// object = {};
// object["firstlevelprop.secondlevelprop"] = "something" =to=> object["firstlevelprop"]["secondlevelprop"] = "something"
(function () {
var enableExpand = function () {
//We dont want the method to appear in the object and mess with the rest of our object's properties
Object.defineProperty(this, "expand", {
enumerable: false, // Not visible
configurable: false, // Not configurable
value: function () {
var nodes, object, value;
for (var prop in this) {
// If there is inside the object a property with dot characters e.g: `obj['user.name']`
if (this.hasOwnProperty(prop) && prop.indexOf(".") > -1) {
// Initialize the object which will hold the reference to the property e.g : `obj['user']['name']`
object = this;
value = this[prop];
// then decompose the nesting of the properties in an array
nodes = prop.split(".");
// Iterate through the array of nodes starting from the 1st level node and going deeper
nodes.forEach(function(node,index,arr){
// If last reached assign it the value
if (!arr[index+1]) {
object[node] = value;
}else{
// If not exists, create an object.
object[node] = object[node] || {};
}
object = object[node];
});
// Delete the initial one which is now translated to nested level properties
delete(this[prop]);
}
}
}
});
};
// Integrate it to object .
enableExpand.call(Object.prototype);
})();
// Now can be used to an object as:
// object["firstlevelprop.secondlevelprop"] = "something";
// object.expand();
// conosle.log(object.firstlevelprop.secondlevelprop); //"something"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment