打印嵌套对象的值

时间:2016-10-20 17:11:13

标签: javascript arrays loops object

给定一个变量库......

 var library = {
   tracks: { t01: { id: "t01",
               name: "Code Monkey",
               artist: "Jonathan Coulton",
               album: "Thing a Week Three" },
        t02: { id: "t02",
               name: "Model View Controller",
               artist: "James Dempsey",
               album: "WWDC 2003"},
        t03: { id: "t03",
               name: "Four Thirty-Three",
               artist: "John Cage",
               album: "Woodstock 1952"}
      },
   playlists: { p01: { id: "p01",
                  name: "Coding Music",
                  tracks: ["t01", "t02"]
                },
           p02: { id: "p02",
                  name: "Other Playlist",
                  tracks: ["t03"]
                }
         }
 }

...我想以下列形式打印我图书馆中所有播放列表的列表:

p01: Coding Music - 2 tracks 
p02: Other Playlist - 1 tracks

我的代码返回给我:

 { id: 'p01', name: 'Coding Music', tracks: [ 't01', 't02' ] }
 { id: 'p02', name: 'Other Playlist', tracks: [ 't03' ] }

代码:

var keys = Object.keys(library.playlists);
for(var i = 0; i < keys.length; i++) {
  var key = keys[i];
  console.log(library.playlists[key]);
}

我是否需要修改代码以获得正确的结果?

1 个答案:

答案 0 :(得分:1)

您可以像这样使用Object.keys()forEach()循环。

&#13;
&#13;
var library = {"tracks":{"t01":{"id":"t01","name":"Code Monkey","artist":"Jonathan Coulton","album":"Thing a Week Three"},"t02":{"id":"t02","name":"Model View Controller","artist":"James Dempsey","album":"WWDC 2003"},"t03":{"id":"t03","name":"Four Thirty-Three","artist":"John Cage","album":"Woodstock 1952"}},"playlists":{"p01":{"id":"p01","name":"Coding Music","tracks":["t01","t02"]},"p02":{"id":"p02","name":"Other Playlist","tracks":["t03"]}}}

var o = library.playlists;
var result = Object.keys(o).forEach(function(e) {
  var str = e + ': ' + o[e].name + ' - ' + o[e].tracks.length + ' tracks';
  console.log(str)
})
&#13;
&#13;
&#13;