2013-10-30 40 views
0

嗨在javascript中我必須從字符串創建對象樹如下如何從字符串創建對象樹中的Java腳本

「組1:節點1:性能,組1:節點2:性能,第2組:節點2:性能,組2:節點3:性能,第2組:節點1:性能,第3組:節點2:屬性」。

在此,性能也:分隔,

我需要的對象樹如下

 
group1 
    node1 
    properties 
    node2 
    properties 
group2 
    node2 
    properties 
    node3 
    properties 
    node1 
    properties 
group3 
    node2 
    properties 

任何機構可以告訴我什麼是做與例子的最佳方式。

+3

我希望你的老師不會看到這個:-P – jAndy

+0

你需要真實的物體還是隻有輸出? – CloudyMarble

+0

我需要根據組 –

回答

2

雖然看起來像一個學校鍛鍊......我認爲你需要看看split()方法。首先分割逗號(,),然後冒號(:)。例如..

看看這個:http://jsfiddle.net/T852c/

var str = 'group1:node1:properties,group1:node2:properties,group2:node2:properties,group2:node3:properties,group2:node1:properties,group3:node2:properties'; 

var result ={}, 
    groups = str.split(','), 
    groupsCount = groups.length; 

for(var i=groupsCount; i--;){ 
    var groupStr = groups[i], 
     split = groupStr.split(':'), 
     groupKey = split[0], 
     nodeKey = split[1], 
     properties = split[2], 
     group = result[groupKey] || (result[groupKey] = {}), 
     node = group[nodeKey] || (group[nodeKey] = {}); 

    node[properties] = { foo: 'bar' };  
} 

console.log(result); 

它可能不是正是你在找什麼,但它可能會幫助您開始。祝你好運!

+0

創建可以訪問的對象。當您拆分它們時,請追加到數組中。 – DannyThunder

相關問題