如何在JavaScript中筛选TMDB接口返回type为Trailer的视频数组项
实现方案
你有两种简单的方式可以实现只输出type="Trailer"的数组项:
方式1:提前过滤数组(推荐)
利用JS数组原生的filter方法,拿到接口返回结果后先筛选符合条件的项,再遍历渲染,修改后的代码如下:
axios .get( "https://api.themoviedb.org/3/movie/" + movieId + "/videos?api_key=1350e4528ff8559ef2b0fa6679f97d84&language=en-US" ) .then((response) => { console.log(response); // 先过滤仅保留type为Trailer的视频 let videos = response.data.results.filter(video => video.type === 'Trailer'); let output = ""; $.each(videos, (index, video) => { output += ` <div class="col-md-4"> <div class="well text-center"> <iframe width="420" height="315" src="https://www.youtube.com/embed/${video.key}"> <h5>${video.type}</h5> </iframe> </div> </div> `; }); //将视频内容渲染到id为videos的div中 $("#videos").html(output); }) .catch((err) => { console.log(err); });
方式2:遍历过程中加判断
如果不想修改原数组,也可以在遍历拼接HTML的时候增加条件判断,只有符合要求的项才拼接:
axios .get( "https://api.themoviedb.org/3/movie/" + movieId + "/videos?api_key=1350e4528ff8559ef2b0fa6679f97d84&language=en-US" ) .then((response) => { console.log(response); let videos = response.data.results; let output = ""; $.each(videos, (index, video) => { // 仅type为Trailer的项才拼接渲染 if (video.type === 'Trailer') { output += ` <div class="col-md-4"> <div class="well text-center"> <iframe width="420" height="315" src="https://www.youtube.com/embed/${video.key}"> <h5>${video.type}</h5> </iframe> </div> </div> `; } }); $("#videos").html(output); }) .catch((err) => { console.log(err); });
注意:判断的时候用严格相等===可以避免隐式类型转换带来的异常问题。
内容的提问来源于stack exchange,提问作者Ant
相关产品推荐
相关产品推荐

