使用javascript过滤JSON数组

时间:2016-02-11 17:44:37

标签: javascript json

我的目标是根据评分过滤JSON电影数组。单击单选按钮时,页面将更新,仅显示具有该评级的电影。截至目前,每次单击一个按钮,它只显示阵列中的所有电影。 以下是我的JSON文件的示例

"movies": {
    "movie": [
      {
        "title": "Aladdin",
        "rating": "G",
        "release date": "11-25-1992",
        "poster": "https://image.tmdb.org/t/p/w185/qsHpmqekgeQKMKL8PWnFsrXTXGs.jpg"
      },

这是我的JS:

 var moviesObj = loadJSON("movies.JSON");
 var movies = moviesObj.movies;


 var movies = movies.movie;

 function filter_movies(rating) {
   var array = [];

   for (var i = 0; i < movies.length; i++) {
     var title = movies[i].title;
     var rating = movies[i].rating;
     var release_date = movies[i]["release date"];
     var poster = movies[i].poster;

     if (movies.rating === rating) {
       array.push(rating);
     }
     console.log(array);
   }

   function display_movies(movies) {
     var moviegrid = "";
     for (var i = 0; i < movies.length; i++) {
       //retrieve movie details and store them in variables to be displayed

       title = movies[i].title;
       rating = movies[i].rating;
       release_date = movies[i]["release date"];
       poster = movies[i].poster;

       //start a new row in the grid
       if (i % 6 == 0) {
         moviegrid += "<div class='row'>";
       };
       //display a movie inside a div block
       moviegrid += "<div class='col'><p><img src='" + poster + "'><span>" + title + "<br>Rated " +
         rating + "<br>" + release_date + "</span></p></div>";

       //close the row in the grid
       if (i % 6 == 5) {
         moviegrid += "</div>";
       };
     };
     //display movies in a div block with the id "moviegrid".
     document.getElementById('moviegrid').innerHTML = moviegrid;
   };
   display_movies(movies);

 };

1 个答案:

答案 0 :(得分:1)

正如评论中暗示的那样,您应该使用filter。它简单,功能更强大,更容易阅读正在发生的事情。您还应该将您的功能分开一点:

function filterByRating(rating) {
    return moviesObj.movies.movie.filter(function (movie) {
        return (movie.rating == rating);
    });
}

function display_movies(movies) {
    var moviegrid = "";
    for (var i = 0; i < movies.length; i++) {
        //retrieve movie details and store them in variables to be displayed

        //start a new row in the grid
        if (i % 6 == 0) {
            moviegrid += "<div class='row'>";
        };
        //display a movie inside a div block
        moviegrid += "<div class='col'><p><img src='" + movies[i].poster + "'><span>" + movies[i].title + "<br>Rated " +
                movies[i].rating + "<br>" + movies[i]["release date"] + "</span></p></div>";

        //close the row in the grid
        if (i % 6 == 5) {
            moviegrid += "</div>";
        }
    }
    //display movies in a div block with the id "moviegrid".
    document.getElementById('moviegrid').innerHTML = moviegrid;
}

现在你所要做的就是:

display_movies(filterByRating('G'));