JavaScript 对象为空

JavaScript object is emtpy

我正在使用 spotify API 转储用户的所有播放列表,以及包含的曲目名称。我想出了如何请求该信息并尝试将其存储在一个散列中,在该散列中可以通过播放列表名称 (hash[playlistName] = [track1, track2, etc]) 找到一组曲目。当我 console.log 这个时,一切看起来都很好。

但是当我尝试使用手柄条助手来遍历它并显示所有内容时,JavaScript 认为该对象是空的。这是一些代码:

//helper that will display eventually, but right now logs "undefined"
Handlebars.registerHelper('read_hash', function(hash){
    console.log(hash.length); //undefined
    console.log(Object.keys(hash); //undefined
    console.log(hash); //looks fine.. results in screenshot..
});

//ajax request that successfully get's all of the playlist data I want
        $.ajax({
            url: 'https://api.spotify.com/v1/me/playlists',
            headers: {
              'Authorization': 'Bearer ' + access_token
            },
            success: function(response) {
              //make a new hash and put in template
              var processed = 0;
              response.items.forEach(function(e){
                var playlistName = e.name;
                //get tracks by nesting a request lol
                $.ajax({
                  url: e.tracks.href,
                  headers: {
                    'Authorization': 'Bearer ' + access_token
                  },
                  success: function(responseTwo) { //returns track objects
                    playlists[playlistName] = responseTwo.items;
                    processed++;
                  }
                }).done(function(){
                  if(processed >= response.items.length)
                  {
                    playlistPlaceholder.innerHTML = playlistTemplate({Playlists: playlists}); //get playlists
                  }
                });
              });

//handle bars template with call to read_hash
<script id="playlist-template" type="text/x-handlebars-template">
  <h1>playlists</h1>
  <table>
    <tr>
      <th>playlist</th>
      <th>tracks</th>
    </tr>
    {{read_hash Playlists}}
  </table>
</script>

此外,当我从 read_hash 控制台记录 JSON.stringify(hash) 时,我得到了我想要的结果,所以...也许有什么用?

长度属性只适用于数组,响应为对象

 var property = {"test object track 123":"test"};
 console.log(property.length); //shows undefined

此外,registerHelper 语句必须生成错误,因为没有右括号 遍历属性

//show error "closed parenthesis"
console.log(Object.keys(hash); //undefined

//helper that will display eventually, but right now logs "undefined"
Handlebars.registerHelper('read_hash', function(hash){
        for (var playlist in hash) {
            console.log("the length of item is" + hash[playlist].length);
        }
});

我利用 ajax 完成回调修复了它。可能有一种更有条理的方法来解决这个问题,但这是我的解决方案:

ajax 请求转储播放列表数据:

$.ajax({
    url: 'https://api.spotify.com/v1/me/playlists',
    headers: {
      'Authorization': 'Bearer ' + access_token
    },
    success: function(response) {
      //make a new hash and put in template
      var processed = 0;
      response.items.forEach(function(e){
        var playlistName = e.name;
        //get tracks by nesting a request lol
        $.ajax({
          url: e.tracks.href,
          headers: {
            'Authorization': 'Bearer ' + access_token
          },
          success: function(responseTwo) { //returns track objects
            playlists[playlistName] = responseTwo.items;
            processed++;
          }
        }).done(function(){
          if(processed >= response.items.length)
          {
            playlistPlaceholder.innerHTML = playlistTemplate({Playlists: playlists}); //get playlists
          }
        });
      });
      //console.log(playlists);
      $('#login').hide();
      $('#loggedin').show();
    }
});

解析关联数组的把手助手:

Handlebars.registerHelper('read_hash', function(hash){
  jsonHash = JSON.parse(JSON.stringify(hash));
  var html = "<table style='width:5px'><tr><th>Playlist</th><th>Track</th></tr>"; //stores markup to write and return at end
  for(var playlistName in jsonHash)
  {
    var playlistTracks = jsonHash[playlistName];
    html = html + "<tr><td>" + playlistName + "</td><td><ul>";
    for(var i = 0; i < playlistTracks.length; i++)
    {
      html =  html + "<li>" + playlistTracks[i].track.name + "</li>";
    }
    html = html + "</ul></td></tr>";
  }
  console.log(html + "</table>");
  return new Handlebars.SafeString(html + "</table>");
});

要显示的把手模板:

<script id="playlist-template" type="text/x-handlebars-template">
  <h1>playlists</h1>
  {{read_hash Playlists}}
  <table>
    <tr>
      <th>playlist</th>
      <th>tracks</th>
    </tr>
  </table>
</script>