Shortening to declaring properties of an empty object in Javascript, are there any?

I need to declare many properties of an object in my script, and I wonder if there is a way to shorten this:

Core.registry.taskItemSelected; Core.registry.taskItemSelected.id; Core.registry.taskItemSelected.name; Core.registry.taskItemSelected.parent; Core.registry.taskItemSelected.summary; Core.registry.taskItemSelected.description; 
+7
source share
2 answers

Does it work?

 Core.registry.taskItemSelected = { id: null, name: null, parent: null, ... }; 
+10
source

Something like this should work:

 var props = ["id", "name", "parent", ...]; Core.registry.taskItemSelected = {}; for (var i = 0; i < props.length; i++) Core.registry.taskItemSelected[props[i]] = ""; 

Edit: following the OP comments, here is the best version with the same end result:

 Object.prototype.declare = function (varArray) { for (var i = 0; i < varArray.length; i++) { this[varArray[i]] = {}; } }; //usage: var props = ["id", "name", "parent"]; Core = {}; Core.declare(props); 

And a live test case: http://jsfiddle.net/5fRDc/

+1
source

All Articles