通过点语法字符串路径访问对象 [英] access object through dot-syntax string path
问题描述
如何通过字符串 path.to.obj
myobject [path] [to] [obj] >?我想调用函数 Settings.write('path.to.setting','settingValue')
哪个会写'settingValue'
到 settingObj [路径] [到] [设置]
。如果没有 eval()
,我怎么能这样做?
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.
推荐答案
你可以使用 str.split()
为此:
path = pathString.split('.');
settingObj[path[0]][path[1]][path[2]] = settingValue;
str.split()
将分开变量到一个数组中,在你指定的字符的位置分割。
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:
(function(){
var o = {}, c = window.Configure = {};
c.write = function(p, d)
{
var ps = p.split('.'), co = o;
for(var i = 0; i < ps.length - 1; i++)
{
co = (co[ps[i]])? co[ps[i]] : co[ps[i]] = {};
}
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;
}
c.write('path.to.property', 'setting');
alert(c.read('path.to.property'));
})();
这篇关于通过点语法字符串路径访问对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!