2013-08-29 39 views
0

我試着整天來解決這個問題:節點/快速目錄瀏覽

我有子目錄的目錄,FE:

| Music Artist 1 
| - Album Nr 1 
| -- Track 1 
| -- Track 2 
| -- ... 
| - Album Nr 2 
| -- Track 1 
| -- Track 2 
| -- ... 
| Music Artist 2 
| - Album Nr 1 
| -- Track 1 
| -- Track 2 
| -- ... 

現在,我將這些目錄循環 - 與添加所有細節到一個數組/對象。 因此,它應該是這樣的:

[ { artist: Music Artist 1, album { title: Album Nr1, songs: { title: Track 1 } ... } ] 

讓所有目錄名/文件是沒有問題的。我只是不明白如何創建數組:(

在先進的感謝

編輯: 這是我的嘗試:http://pastebin.com/vWnbvu5m

+0

也許我錯過了一些東西,但是.push()有什麼問題? –

+0

嗯,這可能很簡單...但我是一個總的JS /節點。 如果我在我的目錄循環之前做了一個 var array = [] 我不知道如何通過使用.push() – Andreas

回答

1

您可以創建artist對象和push()每一個你創建成的陣列。同樣,albumsong可以是對象push()編成對應附連到它們的父對象陣列。

var artists = []; 
// for each artist we have 
    var artist = {}; 
    artist.name = 'Music Artist 1'; 
    artist.albums = []; 
    // for each album we have 
     var album = {}; 
     album.title = 'Album Nr1' 
     album.songs = []; 
     // for each song that we have 
      var song = {}; 
      song.title = 'Track 1'; 
      album.songs.push(song); 
     // end song loop 
     artist.albums.push(album); 
    // end album loop 
    artists.push(artist) 
// end artist loop 

如果您隨後需要JSON格式的此信息,則可以使用JSON解析器對其進行解析。或者,您可以編程讀取每個artist的數據,方法是循環訪問artists陣列。

// returns name of first artist in array 
artists[0].name; 

// returns title of first album by first artist in respective arrays 
artists[0].albums[0].title; 

// returns title of first song in first album by first artist in respective arrays 
artists[0].albums[0].songs[0].title; 
+0

來處理鍵/值因爲你有'recursion'標記,我假設你正在遞歸目錄。如果您需要遞歸應用這個幫助,請將您的代碼添加到問題中並讓我知道。乾杯! – Michal

+0

感謝您的回覆!我的嘗試: http://pastebin.com/vWnbvu5m – Andreas