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?
arrayPositionit looks correct, why not make your code above into a working snippet?