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.
You can use
str.split()for that:str.split()will separate the variable into an array, split at the locations of the character you specify.This is just the root of the operation of course, and assumes proper input.
Edit: Since the paths need to be of variable length, here’s an updated version edited from the syntax you’ve shown above: