2012-12-11 27 views
1

我想動態地形成一個嵌套的樹形對象,如下面使用JavaScript,有人可以讓我知道實現這一目標的最佳方式?如何在Javascript中形成嵌套的對象

var contextpath= { 
     text: "TreeRoot", 
     items: [ { 
      text: "subgroup1" , 
      items: [ { 
       text: "subgroup2", 
       items: [ { 
        text: "subgroup3", 
        items: [ { 
         text: "subgroup4", 
         items: [ { 
          text: "subgroup5" 
         }] 
        }] 
       }] 
      }] 
     }] 
    }; 

我已經劃定,我想轉換爲對象(即可以作爲DAT源樹組件)的字符串。

var path =「TreeRoot | subgroup1 | subgroup2」;

試圖實現類似下面的內容,但使用遞歸/循環使用較少數量的變量。

var contextpathText= {}; 
    contextpathText.text ="TreeRoot"; 

    var childObject={}; 
    var items=[]; 
    childObject.text ="subgroup1"; 
    items.push(childObject); 
    contextpathText.items=(items); 
+1

看起來你確實沒問題。 http://www.whathaveyoutried.com –

+0

你想達到什麼目的?創建這個對象?什麼是參數?你有一個你想要變換的數組,你只是想創建一個像這樣的'n'深層對象,或者是什麼? –

+0

subgroup2是subgroup1的子組? – Christophe

回答

2

你需要一個深度計數器和存儲您正在使用的對象的當前水平。

var obj = {text:''}, parent, child, i = 0; 
obj.text = 'TreeRoot'; 
parent = obj; 
while (++i <= 5) { 
    if (parent.items === undefined) parent.items = []; // because you don't have an items on the last subgroup you can't put it in the object literal 
    child = {text: 'subgroup'+i}; 
    parent.items.push(child); 
    parent = child; 
} 
parent = child = null; // cleanup 
obj; 

jsbeautifiedJSON.stringify(obj)現在

{ 
    "text": "TreeRoot", 
    "items": [{ 
     "text": "subgroup1", 
     "items": [{ 
      "text": "subgroup2", 
      "items": [{ 
       "text": "subgroup3", 
       "items": [{ 
        "text": "subgroup4", 
        "items": [{ 
         "text": "subgroup5" 
        }] 
       }] 
      }] 
     }] 
    }] 
} 

編輯分隔字符串

var path = 'TreeRoot|subgroup1|subgroup2'; 

var obj = {text:''}, parent, child, levelText = path.split('|').reverse(); 
obj.text = levelText.pop() || ''; 
parent = obj; 
while (levelText.length > 0) { 
    child = {text: levelText.pop()}; 
    if (!parent.items) parent.items = []; 
    parent.items.push(child); 
    parent = child; 
} 
obj; 
1

打我,但我這個代碼去:

var contextpath = { text: "TreeRoot", items: []} 

var items = contextpath.items; 

for(var i = 1; i <= 5; i++) { 
    items.push({ text: "subgroup" + i, items: []}); 
    items = items[0].items; 
} 

父親&對於這類事情,子命名絕對更清晰,但我想表明,您不必首先將新對象聲明爲變量,只需推送對象字面值即可。

哎呀,剛纔注意到你沒有在你想要的結構中有一個items數組。我的代碼創建備用,所以你最終與

// snip 
       text: "subgroup4", 
        items: [ { 
         text: "subgroup5", 
         items: [] 
        }] 
// etc. 
+0

非常感謝!!!!這工作完美:) – Learner

+0

你非常歡迎,但保羅S.的答案更符合你所要求的。 –