pannkakstarta
pannkakstarta

Reputation: 11

JavaScript get one property from an object inside of an array

I have an array of movies objects with the properties: movieName, grade, and position. For example these objects look like:

var movies = [ { movieName: "bee movie", grade: 3, position 1},
               { movieName: "Shrek", grade: 5, position: 2} ];

I want to get the movieName property of an object. To decide which object from the movies array I want the movieName from I create a variable named arrayPosition which is a random number between 0 and the length of the array - 1:

arrayPosition = Math.floor(Math.random() * movies.length );

For example:

var movies = [{
    movieName: "Incredibles",
    grade: 4,
    position: 1
  },
  {
    movieName: "Bolt",
    grade: 5,
    position: 2
  }
];

const arrayPosition = Math.floor(Math.random() * movies.length);

console.log(movies[arrayPosition].movieName);

In this case I would like it to console either "Incredibles" or "Bolt" depending on if arrayPosition is 0 or 1 but it only consoles undefined.

I have seen solutions to similar problems but in those cases the position of the object in the array was not a variable but a decided number. For some reason this difference make it not work. How do I get only the movieName property from an object in the array?

Upvotes: 1

Views: 112

Answers (1)

ksav
ksav

Reputation: 20840

Your example code works correctly.

var movies = [
  { movieName: "bee movie", grade: 3, position: 1},
  { movieName: "Shrek", grade: 5, position: 2},
  { movieName: "Incredibles", grade: 4, position: 1}, 
  { movieName: "Bolt", grade: 5, position: 2}
];

var arrayPosition = Math.floor(Math.random() * movies.length)
console.log(movies[arrayPosition].movieName)

If you knew that you always wanted to console.log the title of the 2nd movie in the array, you could instead do:

var movies = [
  { movieName: "bee movie", grade: 3, position: 1},
  { movieName: "Shrek", grade: 5, position: 2},
  { movieName: "Incredibles", grade: 4, position: 1}, 
  { movieName: "Bolt", grade: 5, position: 2}
];

var arrayPosition = 1

console.log(movies[arrayPosition].movieName)

Remember that:

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's length property minus 1.

Using an invalid index number returns undefined.

Upvotes: 2

Related Questions