The hierarchy of building objects from the string "namespace"

I am trying to write a function that takes a string representing a namespace (for example, "MyCompany.UI.LoginPage") and defines each segment of the namespace as an object if it does not already exist. For example, if "MyCompany.UI.LoginPage" was not an object, it would evaluate this:

MyCompany = {}; MyCompany.UI = {}; MyCompany.UI.LoginPage = {}; 

I would like to do this by listing each character of the argument "namespace" (string) and defining each object when the enumeration reaches the period characters.

How can I list string characters in JavaScript?

+2
source share
2 answers

You can access the characters of a string directly by its index using the String.prototype.charAt method:

 var str = "foo"; for (var i = 0; i < str.length; i++) { alert(str.charAt(i)); } 

But I don’t think you want to traverse the character of the namespace character by character, you can use the String.prototype.split method to get an array containing the namespace levels using a dot character ( . ) As a separator, for example:

 var levels = "MyCompany.UI.LoginPage".split('.'); // levels is an array: ["MyCompany", "UI", "LoginPage"] 

But I think that your question goes further, and I will give you a more advanced starting point, I made a recursive function that will allow you to do exactly what you want, initialize several levels of nested objects using a line:

Application:

 initializeNS('MyCompany.UI.LoginPage'); // that will create a MyCompany global object // you can use it on an object to avoid globals also var topLevel = {}; initializeNS('Foo.Bar.Baz', topLevel); // or var One = initializeNS('Two.Three.Four', {}); 

Implementation:

 function initializeNS(ns, obj) { var global = (function () { return this;})(), // reference to the global object levels = ns.split('.'), first = levels.shift(); obj = obj || global; //if no object argument supplied declare a global property obj[first] = obj[first] || {}; // initialize the "level" if (levels.length) { // recursion condition initializeNS(levels.join('.'), obj[first]); } return obj[first]; // return a reference to the top level object } 

You will need to improve this function, for example, you will need to misinform the string ...

+4
source

Convert the string to an array of characters with this code:

 var $letterArray = []; for (var $i = 1; $i <= $yourString.length; $i++) { $letterArray[$i] = $yourStringtring.substring(($i - 1), $i); } 

You can then list each character in the $letterArrary string $letterArrary

+1
source

All Articles