2014-08-28 57 views
1

考慮JSON樹結構如下(也可以是n級深),我想創建一個嵌套的無序列表創建一個從JavaScript對象嵌套的無序列表(也可以是n級深)

var data = [{ 
     'text': 'Subjects', 
     'data': [{ 
      'text': 'Geography', 
      'data': [] 
     }, { 
      'text': 'History', 
      'data': [{ 
       'text': 'Ancient History', 
       'data': [] 
      }] 
     }] 
    }, { 
     'text': 'Sports', 
     'data': [] 
    }, { 
     'text': 'Music', 
     'data': [] 
    }]; 

數據嵌套'n'級深。 「數據」內的「數據」位於另一個「數據」內,等等。

輸出應該是這樣的

<ul> 
<li>Subjects 
    <ul> 
     <li>Geography</li> 
     <li>History 
      <ul> 
       <li>Ancient History 
       </li> 
      </ul> 
     </li> 
    </ul> 
</li> 
<li>Sports 
</li> 
<li>Music 
</li> 

function json_tree(object) { 
    var json = "<ul>"; 
    for (prop in object) { 
     var value = object[prop]; 
     switch (typeof(value)) { 
      case "object": 
       json += "<li>" + value.text + json_tree(value) + "</li>"; 
       break; 
      default: 
       json += "<li>" + value.text + "</li>"; 
     } 
    } 
    return json + "</ul>"; 
} 

我曾嘗試使用上面的代碼試過了,但是這並不能產生需要的結果。

+5

不知道你「問。請澄清,並告訴我們您嘗試了什麼,以及爲什麼它不起作用。 – amphetamachine 2014-08-28 15:44:50

+1

你想得到什麼結果?你試過什麼了?你卡在哪裏?我傾向於關閉作爲[訪問/進程(嵌套)對象,數組或JSON副本](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – 2014-08-28 15:47:35

+1

*「我嘗試過使用上面的代碼,但是這不會產生所需的結果。」*您得到了哪個結果? – 2014-08-28 16:22:36

回答

1

您當前的邏輯會發現下面的鍵for ... in循環:

0 
'text' 
'data' 

檢索OBJ [0]作品如預期的Text屬性,但:

obj['text'].text === undefined 
obj['data'].text === undefined 

jsFiddle):

Subjects 
    undefined 
    undefined 
     Geography 
      undefined 
      undefined 
     History 
      undefined 
      undefined 
      Ancient History 
       undefined 
       undefined 
Sports 
    undefined 
    undefined 
Music 
    undefined 
    undefined 

我已經將迭代器更改爲使用簡單的for循環而不是for ... in。

此外,還可以簡化檢查,只尋找在當前索引對象數據的長度,以確定是否需要再次遞歸到json_tree:

function json_tree(data) { 
    var json = "<ul>"; 

    for(var i = 0; i < data.length; ++i) { 
     json = json + "<li>" + data[i].text; 
     if(data[i].data.length) { 
      json = json + json_tree(data[i].data); 
     } 
     json = json + "</li>"; 
    } 
    return json + "</ul>"; 
} 

demo fiddle

相關問題