How can I access myobject[path][to][obj]
via a string path.to.obj
? I want to call a function Settings.write('path.to.setting', 'settingValue')
which would write 'settingValue'
to settingObj[path][to][setting]
. How can I do this without eval()
?
I finally figured it out around the same time as one of the users below answered it. I'll post mine here with documentation on how it works if anyone is interested.
(function(){
var o = {}, c = window.Configure = {};
c.write = function(p, d)
{
// Split the path to an array and assaign the object
// to a local variable
var ps = p.split('.'), co = o;
// Iterate over the paths, skipping the last one
for(var i = 0; i < ps.length - 1; i++)
{
// Grab the next path's value, creating an empty
// object if it does not exist
co = (co[ps[i]])? co[ps[i]] : co[ps[i]] = {};
}
// Assign the value to the object's last path
co[ps[ps.length - 1]] = d;
}
c.read = function(p)
{
var ps = p.split('.'), co = o;
for(var i = 0; i < ps.length; i++)
{
co = (co[ps[i]])? co[ps[i]] : co[ps[i]] = {};
}
return co;
}
})();
The reason I was having problems is you have to skip the last path. If you include the last path, you end up just assigning an arbitrary object.