Creating a dynamic Javascript object tree using an array?
Not sure if this c开发者_如何转开发an even be done, but I'll ask anyway:
Suppose if I have an array of names:
['bob', 'sue', 'dan']
And I want to dynamically create an object from those names:
bob.sue.dan = 5;
Is it possible?
Here you go, will preserve existing objects:
var namespace = function(name, separator, container){
var ns = name.split(separator || '.'),
o = container || window,
i,
len;
for(i = 0, len = ns.length; i < len; i++){
o = o[ns[i]] = o[ns[i]] || {};
}
return o;
};
e.g. usage:
namespace("com.example.namespace");
com.example.namespace.test = function(){
alert("In namespaced function.");
};
or for your example using an array.
var ns = ['bob', 'sue', 'dan'];
namespace(ns.join('.'));
bob.sue.dan.foobar = true;
or extending an existing object:
var bob = {}
namespace("foo.bar",".",bob);
bob.foo.bar = true;
Edit: updated as requested:
var namespace = function(name, separator, container, val){
var ns = name.split(separator || '.'),
o = container || window, i, len;
for(i = 0, len = ns.length; i < len; i++){
var v = (i==len-1 && val) ? val : {};
o = o[ns[i]] = o[ns[i]] || v;
}
return o;
};
namespace("bob.sue.dan",null,null,5);
alert(bob.sue.dan);
See working example: http://jsfiddle.net/herostwist/hu6j9/
Then you can do:
function makeOjectTree(propNames) {
var name;
var o = {};
var result = o;
for (var i=0, iLen=propNames.length; i<iLen; i++) {
name = propNames[i];
if (!o[name]) {
o[name] = {};
o = o[name];
}
}
return result;
}
var names = ['bob', 'sue', 'dan'];
var objs = [];
for(var i=0; i<names.length; i++) {
objs.push(names[i]);
var val = (i==names.length-1) ? "5" : "{}";
eval(objs.join(".") + " = " + val);
}
alert(bob.sue.dan);
Demo: http://jsfiddle.net/EpZm2/1/
sure you can ...
var obj = 5;
var yourarray = ['bob', 'sue', 'dan'];
yourarray = yourarray.reverse();
for(e in yourarray) {
var tmpobj = obj;
obj = new Object();
obj[yourarray[e]] = tmpobj;
// if you already have an object
if (e+1 == yourarray.length) {
your_current_existing_object[yourarray[e]] = tmpobj;
}
}
Yes this is possible.
You can define new properties on an object this way:
var obj = {};
obj["bob"] = {};
obj["bob"]["sue"] = {};
obj["bob"]["sue"]["dan"] = 5;
So you can also do it with an array of property names ;)
精彩评论