繁体   English   中英

迭代嵌套数据 JS

[英]Iterating over nested data JS

我对编程有点陌生,对 JS 也很陌生,所以我为初学者的问题道歉。

我正在尝试遍历这些数据并获取每个曲目的名称和艺术家,但我遇到了问题。 目前我正在尝试这样的事情。

如果有人有任何见解或建议,我将不胜感激。

我正在使用带有 JS 前端的 rails 后端。 谢谢!

function selectTracks(){
      fetch(BACKEND_URL)
      .then(response => response.json())
      .then(playlist  => {
          playlist.data.forEach(playlist => {                        
            `<h4> ${playlist.attributes.track.name}</h4>
            <h4>${playlist.attributes.track.artist}></h4>  `
            // let newPlaylist = new Playlist(playlist, playlist.attributes) 
            console.log(fetch)
          //  document.getElementById("playlist-container").innerHTML += newPlaylist.renderPlaylistCard();
           debugger
          }
      )}
  )
}

我的序列化器看起来像这样

{
  data: [
    {
      id: "1",
      type: "playlist",
      attributes: {
        name: "Country Songs",
        id: 1,
        track_id: 10,
        track: {
          id: 10,
          name: "First Song",
          artist: "Randy",
          created_at: "2020-06-17T02:09:07.152Z",
          updated_at: "2020-06-17T02:09:07.152Z"
        }
      },
      relationships: {
        track: {
          data: {
            id: "10",
            type: "track"
          }
        }
      }
    }
  ]
}

您需要将forEach替换为map 'forEach loop doesn't return anything. But the loop doesn't return anything. But the map method return an array. (An array of HTML elements in your case method return an array. (An array of HTML elements in your case

fetch(BACKEND_URL)
      .then(response => response.json())
      .then(playlist  => {
          return playlist.data.map(playlist => {                        
            `<h4> ${playlist.attributes.track.name}</h4>
            <h4>${playlist.attributes.track.artist}></h4>  `
            // let newPlaylist = new Playlist(playlist, playlist.attributes) 
            console.log(fetch)
          //  document.getElementById("playlist-container").innerHTML += newPlaylist.renderPlaylistCard();
           debugger
          }
      )}
  )

假设 BACKEND_URL 正确且 json 有效,您的代码在技术上有效。 但是,在其当前的 state 中,它对数据没有任何作用。 例如,如果您 output 使用 h4 标签,您应该会看到它们被写入屏幕。

document.write(
  `<h4> ${playlist.attributes.track.name}</h4>
   <h4>${playlist.attributes.track.artist}</h4>  `
)

或者,您可以记录这些值以证明您正在正确处理数据:

console.log(playlist.attributes.track.name, playlist.attributes.track.artist)

如果没有,接下来要检查的是您的 json 的有效性。 我假设您从浏览器中复制了 json,这将去除一些引号以提高可读性。 查看源代码以确保键名正确地用引号括起来,如下所示:

{
  "data": [
    {
      "id": "1",
      "type": "playlist",
      "attributes": {
        "name": "Country Songs",
...

如果您使用 ActiveModel 序列化程序,则它们的格式应正确。

如果您的 json 有效,并且您可以将 h4 标签写入包含正确数据的页面,那么问题可能出在您的播放列表 class 上。

另一个诊断 fetch() 问题的便捷工具是 Chrome 开发者工具。 Go 到网络并单击 XHR 过滤器。 这将允许您检查获取请求并查看响应是否有效以及数据是否符合您的预期。 其他浏览器也有类似的功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM