2011-04-13 83 views
4

我见过很多相关的问题和谷歌搜索结果,但没有一个与我的问题相符。Javascript string to object reference(without eval()or indexes)

我收到了一个字符串“header.h2”,我想要插入到'var objects'。 所以我想objects.header.h2(其中包含更多的哈希数据)。

但是,我不想使用eval()或经常建议的buttons[],原因很明显,buttons[header.h2]不起作用,我需要buttons[header][h2]

那么我该如何保持对象符号,或者在最坏的情况下解决我的问题?

回答

8

只是一种可能的方式速写:

您的数据

var data = [ 
    {foo: 1, bar: 2, foobar: [ 
     'a', 'b', 'c' 
    ]}, 
    {foo: 1, bar: 2, foobar: [ 
     'd', 'e', 'f' 
    ]}, 
    {foo: 1, bar: 2, foobar: [ 
     'g', 'h', 'i' 
    ]} 
]; 

var accessor = '1.foobar.2'; 

使用辅助函数

function helper(data, accessor) { 
    var keys = accessor.split('.'), 
     result = data; 

    while (keys.length > 0) { 
     var key = keys.shift(); 
     if (typeof result[key] !== 'undefined') { 
      result = result[key]; 
     } 
     else { 
      result = null; 
      break; 
     } 
    } 

    return result; 
} 

,或将其提供给所有对象 :(亲自,我不喜欢这个......)

Object.prototype.access = function (accessor) { 
    var keys = accessor.split('.'), 
     result = this; 

    while (keys.length > 0) { 
     var key = keys.shift(); 
     if (typeof result[key] !== 'undefined') { 
      result = result[key]; 
     } 
     else { 
      result = null; 
      break; 
     } 
    } 

    return result; 
}; 

调试输出

console.log(
    helper(data, accessor), // will return 'f' 
    data.access(accessor) // will return 'f' 
); 
+0

那么分裂点,然后遍历它们并将它们设置在多维数组中?看起来不错! – 2011-04-13 09:21:40

3

我想创造出创造每点符号的字符串的对象 “填充” 的方法是给出:

var populate = function(obj, str) { 
    var ss=str.split(/\./), len=ss.length, i, o=obj; 
    for (i=0; i<len; i++) { 
    if (!o[ss[i]]) { o[ss[i]] = {}; } 
    o = o[ss[i]]; 
    } 
    return obj; 
}; 

var objects = populate({}, 'header.h2'); 
objects.header.h2; // => Object {} 
populate(objects, 'foo.bar.gah.zip'); 
objects.foo.bar.gah.zip; // => Object {} 

需求测试,但应该让你更接近你的目标。