I'm trying to list all NESTED values of an array in javascript, but get only the 1st value of each in the array

拥有回忆 提交于 2020-01-24 19:03:10

问题


I am a newbe at Template Literals, mapping and javascript. I have an array and I'm using Template Literals to insert a div into an html. I'm mapping the array of 4 albums. In the array I have lists of tracks for each album. I'm trying to list one track list for each album at a time. When I run the code I only get the 1st track of each album instead of the 1st track list of the 1st album. How can I list all the values in the first nest of the array? The code is as follows:

// JavaScript Document

var albumData =[
	{	
		"imageUrl": "music_imgs/covers/genpx1.png",
		"artist": "Gen1artist",
		"name": "Gen1name",
		"release":"released 2017",
		"tracks":[
		{
			"TrackNumber": "1",
			"link":"media/file_example_MP3_700KB.mp3",
			"song":"Gen1Track1",
			"songimgUrl": "music_imgs/availsound.png",
			"duration":"2:47"
		},
		{
			"TrackNumber": 2,
			"song":"Gen1Track2",
			"duration":"0:00"
		},
		{
			"TrackNumber": 3,
			"link":"media/ffile_example_MP3_700KB.mp3",
			"song":"Gen1Track3",
			"songimgUrl": "music_imgs/availsound.png",
			"duration":"2:52"
		},
		{
			"TrackNumber": 4,
			"link":"media/file_example_MP3_700KB.mp3",
			"song":"Gen1Track4",
			"songimgUrl": "music_imgs/availsound.png",
			"duration":"3:25"
		}

		]
	},
	{
		"imageUrl": "music_imgs/covers/genpx2.png",
		"artist": "Gen2artist",
		"name": "Gen2name",
		"release":"released 201x",
		"tracks":[
		{
			"TrackNumber": 1,
			"link":"media/file_example_MP3_700KB.mp3",
			"song":"Gen2Track1",
			"songimgUrl": "music_imgs/availsound.png",
			"duration":"4:15"
		},
		{
			"TrackNumber": 2,
			"song":"Gen2Track2",
			"duration":"3:22"
		},
		{
			"TrackNumber": 3,
			"song":"Gen2Track3",
			"duration":"3:13"
		},
		{
			"TrackNumber": 4,
			"song":"Gen2Track4",
			"duration":"5:01"
		}
		]
	},
	{
		"imageUrl": "music_imgs/covers/genpx3.png",
		"artist": "Gen3artist",
		"name": "Gen3name",
		"release":"released 2014",
		"tracks":[
		{
			"TrackNumber": 1,
			"link":"media/file_example_MP3_700KB.mp3",
			"song":"Gen3Track1",
			"songimgUrl": "music_imgs/availsound.png",
			"duration":"4:04"
		},
		{
			"TrackNumber": 2,
			"song":"Gen3Track2",
			"duration":"0:00"
		},
		{
			"TrackNumber": 3,
			"song":"Gen3Track3",
			"duration":"0:00"
		},
		{
			"TrackNumber": 4,
			"song":"Gen3Track4",
			"duration":"0:00"
		}

		]
	},
	{
		"imageUrl": "music_imgs/covers/genpx4.png",
		"artist": "Gen4artist",
		"name": "Gen4name",
		"release":"released 2006",
		"tracks":[
		{
			"TrackNumber": 1,
			"link":"media/file_example_MP3_700KB.mp3",
			"song":"Gen4Track1",
			"songimgUrl": "music_imgs/availsound.png",
			"duration":"3:03"
		},
		{
			"TrackNumber": 2,
			"link":"media/file_example_MP3_700KB.mp3",
			"song":"Gen4Track2",
			"songimgUrl": "music_imgs/availsound.png",
			"duration":"4:36"
		},
		{
			"TrackNumber": 3,
			"link":"media/file_example_MP3_700KB.mp3",
			"song":"Gen4Track3",
			"songimgUrl": "music_imgs/availsound.png",
			"duration":"2:52"
		},
		{
			"TrackNumber": 4,
			"song":"Gen4Track4",
			"duration":"0:00"
		}
		]
	}
]
var songlist=$(`${albumData.map(function(songs) {
			for (var a in songs.tracks) {
          return `
		  	<li class="songlist">
				<span class="songs">${songs.tracks[a].TrackNumber + ".&nbsp;" + songs.tracks[a].song}</span>
				<span class="time">${songs.tracks[a].duration}</span>
			</li>
	  `}
	  }).join('')
}`)
var playlist=$('#playlist');
$( playlist ).append( songlist );
@charset "UTF-8";
/* CSS Document */
*{
	box-sizing: border-box;
}
body{
	text-align:center;
	font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
	font-size: 0.8rem;
	font-weight:bold;
	color:#ffffff;
	background-color:#000000;
}
#playlist{
	float:right;
	width:60%;
	padding:10px;
  	background-color:#373636;
	border:dashed #F7060A;
}
.tracklist{
	margin:5px;
	cursor:pointer;
}
.songs{
	float:left;
}
.time{
	float:right;
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>playlist12-29.1</title>
<link href="mus_css/playlist12-29.1.css" rel="stylesheet" type="text/css">
</head>

<body>
        <div id="playlist">
        <!---<li class="tracklist">
				<span class="songs"></span>
				<span class="time"></span>
			</li>--->
        </div>
	<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
	<script src="mus_js/playlist12-29.1.js"></script>
    </body>
</html>

回答1:


Because you have a return statement inside your foreach loop. So that will return the first value enumerated in foreach. Instead you should use another map to generate a list from tracks array like below

var songlist = $(`${albumData.map(function(songs) {
            return songs.tracks.map(r=>`
      <li class="tacklist">
                <span class="songs">${r.TrackNumber + ".&nbsp;" + r.song}</span>
                <span class="time">${r.duration}</span>
            </li>
      `).join('');
      }).join('')
}`);

// JavaScript Document

var albumData = [{
    "imageUrl": "music_imgs/covers/genpx1.png",
    "artist": "Gen1artist",
    "name": "Gen1name",
    "release": "released 2017",
    "tracks": [{
        "TrackNumber": "1",
        "link": "media/file_example_MP3_700KB.mp3",
        "song": "Gen1Track1",
        "songimgUrl": "music_imgs/availsound.png",
        "duration": "2:47"
      },
      {
        "TrackNumber": 2,
        "song": "Gen1Track2",
        "duration": "0:00"
      },
      {
        "TrackNumber": 3,
        "link": "media/ffile_example_MP3_700KB.mp3",
        "song": "Gen1Track3",
        "songimgUrl": "music_imgs/availsound.png",
        "duration": "2:52"
      },
      {
        "TrackNumber": 4,
        "link": "media/file_example_MP3_700KB.mp3",
        "song": "Gen1Track4",
        "songimgUrl": "music_imgs/availsound.png",
        "duration": "3:25"
      }

    ]
  },
  {
    "imageUrl": "music_imgs/covers/genpx2.png",
    "artist": "Gen2artist",
    "name": "Gen2name",
    "release": "released 201x",
    "tracks": [{
        "TrackNumber": 1,
        "link": "media/file_example_MP3_700KB.mp3",
        "song": "Gen2Track1",
        "songimgUrl": "music_imgs/availsound.png",
        "duration": "4:15"
      },
      {
        "TrackNumber": 2,
        "song": "Gen2Track2",
        "duration": "3:22"
      },
      {
        "TrackNumber": 3,
        "song": "Gen2Track3",
        "duration": "3:13"
      },
      {
        "TrackNumber": 4,
        "song": "Gen2Track4",
        "duration": "5:01"
      }
    ]
  },
  {
    "imageUrl": "music_imgs/covers/genpx3.png",
    "artist": "Gen3artist",
    "name": "Gen3name",
    "release": "released 2014",
    "tracks": [{
        "TrackNumber": 1,
        "link": "media/file_example_MP3_700KB.mp3",
        "song": "Gen3Track1",
        "songimgUrl": "music_imgs/availsound.png",
        "duration": "4:04"
      },
      {
        "TrackNumber": 2,
        "song": "Gen3Track2",
        "duration": "0:00"
      },
      {
        "TrackNumber": 3,
        "song": "Gen3Track3",
        "duration": "0:00"
      },
      {
        "TrackNumber": 4,
        "song": "Gen3Track4",
        "duration": "0:00"
      }

    ]
  },
  {
    "imageUrl": "music_imgs/covers/genpx4.png",
    "artist": "Gen4artist",
    "name": "Gen4name",
    "release": "released 2006",
    "tracks": [{
        "TrackNumber": 1,
        "link": "media/file_example_MP3_700KB.mp3",
        "song": "Gen4Track1",
        "songimgUrl": "music_imgs/availsound.png",
        "duration": "3:03"
      },
      {
        "TrackNumber": 2,
        "link": "media/file_example_MP3_700KB.mp3",
        "song": "Gen4Track2",
        "songimgUrl": "music_imgs/availsound.png",
        "duration": "4:36"
      },
      {
        "TrackNumber": 3,
        "link": "media/file_example_MP3_700KB.mp3",
        "song": "Gen4Track3",
        "songimgUrl": "music_imgs/availsound.png",
        "duration": "2:52"
      },
      {
        "TrackNumber": 4,
        "song": "Gen4Track4",
        "duration": "0:00"
      }
    ]
  }
]
var songlist = $(`${albumData.map(function(songs) {
			return songs.tracks.map(r=>`
      <li class="tracklist">
 
				<span class="songs">${r.TrackNumber + ".&nbsp;" + r.song}</span>
				<span class="time">${r.duration}</span>
       
			</li>
      `).join('');
	  }).join('')
}`);
var playlist = $('#playlist');
$(playlist).append(songlist);
@charset "UTF-8";

/* CSS Document */

* {
  box-sizing: border-box;
}

body {
  text-align: center;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 0.8rem;
  font-weight: bold;
  color: #ffffff;
  background-color: #000000;
}

#playlist {
  float: right;
  width: 60%;
  padding: 10px;
  background-color: #373636;
  border: dashed #F7060A;
}

.tracklist {
  margin: 5px;
  cursor: pointer;
  list-style: none;
  clear: both;
}

.songs {
  float: left;
}

.time {
  float: right;
  clear: right;
}
<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <title>playlist12-29.1</title>
  <link href="mus_css/playlist12-29.1.css" rel="stylesheet" type="text/css">
</head>

<body>
  <ul id="playlist">
    <!---<li class="tracklist">
				<span class="songs"></span>
				<span class="time"></span>
			</li>--->
  </ul>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  <script src="mus_js/playlist12-29.1.js"></script>
</body>

</html>

Edit: Those bullets you see normally places at the beginning of an unordered list item. Why you see them in the middle? Because you use styles float:left , float right kind of styles it changes the placement of the bullet. What you can do about it is :

.tracklist {
      margin: 5px;
      cursor: pointer;
      list-style: none; /* remove bullets */
      clear: both; /* fix floating so next item should place correctly*/
}



回答2:


The return inside the function passed to map() is "short-circuiting" the for loop. Here is a version that works with a for loop. It constructs the return value, then returns the value after the for loop is completed:

var songlist = albumData.map(function(songs) {
    let value = ''
    for (var a in songs.tracks) {
        value +=
            `<li class="songlist">
                 <span class="songs">${songs.tracks[a].TrackNumber + ".&nbsp;" + songs.tracks[a].song}</span>
                 <span class="time">${songs.tracks[a].duration}</span>
            </li>`
    }
    return value;
});

// JavaScript Document

var albumData =[
	{	
		"imageUrl": "music_imgs/covers/genpx1.png",
		"artist": "Gen1artist",
		"name": "Gen1name",
		"release":"released 2017",
		"tracks":[
		{
			"TrackNumber": "1",
			"link":"media/file_example_MP3_700KB.mp3",
			"song":"Gen1Track1",
			"songimgUrl": "music_imgs/availsound.png",
			"duration":"2:47"
		},
		{
			"TrackNumber": 2,
			"song":"Gen1Track2",
			"duration":"0:00"
		},
		{
			"TrackNumber": 3,
			"link":"media/ffile_example_MP3_700KB.mp3",
			"song":"Gen1Track3",
			"songimgUrl": "music_imgs/availsound.png",
			"duration":"2:52"
		},
		{
			"TrackNumber": 4,
			"link":"media/file_example_MP3_700KB.mp3",
			"song":"Gen1Track4",
			"songimgUrl": "music_imgs/availsound.png",
			"duration":"3:25"
		}

		]
	},
	{
		"imageUrl": "music_imgs/covers/genpx2.png",
		"artist": "Gen2artist",
		"name": "Gen2name",
		"release":"released 201x",
		"tracks":[
		{
			"TrackNumber": 1,
			"link":"media/file_example_MP3_700KB.mp3",
			"song":"Gen2Track1",
			"songimgUrl": "music_imgs/availsound.png",
			"duration":"4:15"
		},
		{
			"TrackNumber": 2,
			"song":"Gen2Track2",
			"duration":"3:22"
		},
		{
			"TrackNumber": 3,
			"song":"Gen2Track3",
			"duration":"3:13"
		},
		{
			"TrackNumber": 4,
			"song":"Gen2Track4",
			"duration":"5:01"
		}
		]
	},
	{
		"imageUrl": "music_imgs/covers/genpx3.png",
		"artist": "Gen3artist",
		"name": "Gen3name",
		"release":"released 2014",
		"tracks":[
		{
			"TrackNumber": 1,
			"link":"media/file_example_MP3_700KB.mp3",
			"song":"Gen3Track1",
			"songimgUrl": "music_imgs/availsound.png",
			"duration":"4:04"
		},
		{
			"TrackNumber": 2,
			"song":"Gen3Track2",
			"duration":"0:00"
		},
		{
			"TrackNumber": 3,
			"song":"Gen3Track3",
			"duration":"0:00"
		},
		{
			"TrackNumber": 4,
			"song":"Gen3Track4",
			"duration":"0:00"
		}

		]
	},
	{
		"imageUrl": "music_imgs/covers/genpx4.png",
		"artist": "Gen4artist",
		"name": "Gen4name",
		"release":"released 2006",
		"tracks":[
		{
			"TrackNumber": 1,
			"link":"media/file_example_MP3_700KB.mp3",
			"song":"Gen4Track1",
			"songimgUrl": "music_imgs/availsound.png",
			"duration":"3:03"
		},
		{
			"TrackNumber": 2,
			"link":"media/file_example_MP3_700KB.mp3",
			"song":"Gen4Track2",
			"songimgUrl": "music_imgs/availsound.png",
			"duration":"4:36"
		},
		{
			"TrackNumber": 3,
			"link":"media/file_example_MP3_700KB.mp3",
			"song":"Gen4Track3",
			"songimgUrl": "music_imgs/availsound.png",
			"duration":"2:52"
		},
		{
			"TrackNumber": 4,
			"song":"Gen4Track4",
			"duration":"0:00"
		}
		]
	}
]
var songlist=albumData.map(function(songs) {
    let value = ''
		for (var a in songs.tracks) {
        value +=
            `<li class="songlist">
				        <span class="songs">${songs.tracks[a].TrackNumber + ".&nbsp;" + songs.tracks[a].song}</span>
				        <span class="time">${songs.tracks[a].duration}</span>
            </li>`
    }
    return value;
});
var playlist=$('#playlist');
$( playlist ).append( songlist );
@charset "UTF-8";
/* CSS Document */
*{
	box-sizing: border-box;
}
body{
	text-align:center;
	font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
	font-size: 0.8rem;
	font-weight:bold;
	color:#ffffff;
	background-color:#000000;
}
#playlist{
	float:right;
	width:60%;
	padding:10px;
  	background-color:#373636;
	border:dashed #F7060A;
}
.tracklist{
	margin:5px;
	cursor:pointer;
}
.songs{
	float:left;
}
.time{
	float:right;
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>playlist12-29.1</title>
<link href="mus_css/playlist12-29.1.css" rel="stylesheet" type="text/css">
</head>

<body>
        <div id="playlist">
        <!---<li class="tracklist">
				<span class="songs"></span>
				<span class="time"></span>
			</li>--->
        </div>
	<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
	<script src="mus_js/playlist12-29.1.js"></script>
    </body>
</html>



回答3:


Set a tl var to an empty string for each album, then iterate through the song list and += each song to the tl before returning it and moving to the next album.

var albumData = [{"imageUrl":"music_imgs/covers/genpx1.png","artist":"Gen1artist","name":"Gen1name","release":"released 2017","tracks":[{"TrackNumber":"1","link":"media/file_example_MP3_700KB.mp3","song":"Gen1Track1","songimgUrl":"music_imgs/availsound.png","duration":"2:47"},{"TrackNumber":2,"song":"Gen1Track2","duration":"0:00"},{"TrackNumber":3,"link":"media/ffile_example_MP3_700KB.mp3","song":"Gen1Track3","songimgUrl":"music_imgs/availsound.png","duration":"2:52"},{"TrackNumber":4,"link":"media/file_example_MP3_700KB.mp3","song":"Gen1Track4","songimgUrl":"music_imgs/availsound.png","duration":"3:25"}]},{"imageUrl":"music_imgs/covers/genpx2.png","artist":"Gen2artist","name":"Gen2name","release":"released 201x","tracks":[{"TrackNumber":1,"link":"media/file_example_MP3_700KB.mp3","song":"Gen2Track1","songimgUrl":"music_imgs/availsound.png","duration":"4:15"},{"TrackNumber":2,"song":"Gen2Track2","duration":"3:22"},{"TrackNumber":3,"song":"Gen2Track3","duration":"3:13"},{"TrackNumber":4,"song":"Gen2Track4","duration":"5:01"}]},{"imageUrl":"music_imgs/covers/genpx3.png","artist":"Gen3artist","name":"Gen3name","release":"released 2014","tracks":[{"TrackNumber":1,"link":"media/file_example_MP3_700KB.mp3","song":"Gen3Track1","songimgUrl":"music_imgs/availsound.png","duration":"4:04"},{"TrackNumber":2,"song":"Gen3Track2","duration":"0:00"},{"TrackNumber":3,"song":"Gen3Track3","duration":"0:00"},{"TrackNumber":4,"song":"Gen3Track4","duration":"0:00"}]},{"imageUrl":"music_imgs/covers/genpx4.png","artist":"Gen4artist","name":"Gen4name","release":"released 2006","tracks":[{"TrackNumber":1,"link":"media/file_example_MP3_700KB.mp3","song":"Gen4Track1","songimgUrl":"music_imgs/availsound.png","duration":"3:03"},{"TrackNumber":2,"link":"media/file_example_MP3_700KB.mp3","song":"Gen4Track2","songimgUrl":"music_imgs/availsound.png","duration":"4:36"},{"TrackNumber":3,"link":"media/file_example_MP3_700KB.mp3","song":"Gen4Track3","songimgUrl":"music_imgs/availsound.png","duration":"2:52"},{"TrackNumber":4,"song":"Gen4Track4","duration":"0:00"}]}]

let tl

var songlist = $(`${albumData.map(function(songs) {      
    tl = ""
    for (var a in songs.tracks) {
        tl += `
            <li class="songlist">
                <span class="songs">
                    ${songs.tracks[a].TrackNumber + ".&nbsp;" + songs.tracks[a].song}
                </span>
                <span class="time">
                    ${songs.tracks[a].duration}
                </span>
            </li>`
    }
    return tl
}).join('')}`)

var playlist=$('#playlist')

$( playlist ).append( songlist )
*{box-sizing: border-box}
body{
	text-align:center;
	font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
	font-size: 0.8rem;
	font-weight:bold;
	color:#ffffff;
	background-color:#000000;
}
#playlist{
	float:right;
	width:60%;
	padding:10px;
  background-color:#373636;
	border:dashed #F7060A;
}
.songlist{
	margin:5px;
	cursor:pointer;
}
.songs{
	float:left;
}
.time{
	float:right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="playlist"></div>


来源:https://stackoverflow.com/questions/59523320/im-trying-to-list-all-nested-values-of-an-array-in-javascript-but-get-only-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!