Javascript: Mixing Arrays and Objects

Contents

Really what we mean here is that you can have an array of objects, not just simple strings or numbers. And you can reference data in those objects with key:value pairs. Here are several examples of mixing Arrays and Objects together.

//create an array of movies that has the title, the imdb rating and whether or not you have watched it

//v1.0

var movies = [
  {title: "12 Angry Men",
   rating: 4.5,
   status: true},
  {title: "101 Dalmations",
   rating: 3,
   status: true},
  {title: "Avengers 4",
   rating: 5,
   status: false},
]

function movieStatus(theMovie) {
  theMovie.forEach(function (movie){

    if (movie.status === true){
      console.log("You have seen " + "\"" + movie.title + "\"" + " - " + movie.rating + " stars");
    }else{
      console.log("You have not seen " + "\"" + movie.title + "\"" + " - " + movie.rating + " stars");
    };

  })
}

//v.20 - refactored for DRY

var movies = [
  {title: "12 Angry Men",
   rating: 4.5,
   status: true},
  {title: "101 Dalmations",
   rating: 3,
   status: true},
  {title: "Avengers 4",
   rating: 5,
   status: false},
]

function movieStatus(theMovie) {
  theMovie.forEach(function (movie){
    var theRest = "\"" + movie.title + "\"" + " - " + movie.rating + " stars";

    if (movie.status === true){
      console.log("You have seen " + theRest);
    }else{
      console.log("You have not seen " + theRest);
    };

  })
}


//v3.0 - an alternate method
var movies = [
  {title: "12 Angry Men",
   rating: 4.5,
   status: true},
  {title: "101 Dalmations",
   rating: 3,
   status: true},
  {title: "Avengers 4",
   rating: 5,
   status: false},
]

function buildString(movie){
  var result = "You have ";
  if(movie.status){
    result += "watched ";
  } else {
    result += "not seen ";
  }
  result += "\"" + movie.title + "\" - " + movie.rating + " stars";
  return result
}

movies.forEach(function(movie){
  console.log(buildString(movie))
});

And here is version 4, which I did later, and I actually think this is the best:

// the array that we are working with
var movieData = [
  {
    Title: "12 Angry Men",
    Rating: 5,
    hasWatched: true
  },
  {
    Title: "Metropolis",
    Rating: 2,
    hasWatched: false
  },
  {
    Title: "The 3rd Man",
    Rating: 3,
    hasWatched: false
  }
];


//creating a function that loops over the array and prints a string for each item in the array
function printMovieData() {
  movieData.forEach(function(movie) {
    if (movie.hasWatched === true) {
      var watchStatus = " have seen ";
    } else {
      var watchStatus = " have not seen ";
    }
    console.log(
      "You" + watchStatus + movie.Title + " - " + movie.Rating + " stars"
    );
  });
}