You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 16:39:03