2011-04-13 77 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 {} 

需求測試,但應該讓你更接近你的目標。