节点/快速目录浏览

时间:2013-08-29 18:34:04

标签: arrays node.js object recursion express

我整天都在努力解决这个问题:

我有一个包含子目录的目录,例如:

 | 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

1 个答案:

答案 0 :(得分: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;
相关问题