Using plain Javascript, I am trying to access a property, theatricalrelease for all objects in an array, movies.
var movies = [{
"Black Panther" : {
"title" : "Black Panther",
"theatricalrelease" : "2/16/2018"
},
"Infinity War" : {
"title" : "Avengers: Infinity War",
"theatricalrelease" : "5/4/2018"
},
"Captain Marvel" : {
"title" : "Captain Marvel",
"theatricalrelease" : "TBA"
}
}];
for (var i = 0; i < movies.length; i++) {
console.log(movies[i]);
//TRIED
for (var property in movies[i]) {
if (movies[i].hasOwnProperty(property)) {
console.log(property);
}
}
}
}
As you can see, I tried to use another for loop inside another one as I expected it to loop over the object's index names. Instead, logging property gave me the name of each index.
How can I access each movie's theatrical realease?
2 Answers 2
The problem is you have an array of one object and an extra } bracket at the bottom of the code. I made some changes to your array to what I believe you intended. This now prints the theatrical release in your console.log.
var movies = [{
"title" : "Black Panther",
"theatricalrelease" : "2/16/2018"
},{
"title" : "Avengers: Infinity War",
"theatricalrelease" : "5/4/2018"
},{
"title" : "Captain Marvel",
"theatricalrelease" : "TBA"
}];
for (var i = 0; i < movies.length; i++) {
console.log(movies[i]);
console.log('theatrical release', movies[i]['theatricalrelease'])
}
Comments
According to your approach: Only one element:
var movies = [{ "title": "Black Panther", "theatricalrelease": "2/16/2018"}, { "title": "Avengers: Infinity War", "theatricalrelease": "5/4/2018"}, { "title": "Captain Marvel", "theatricalrelease": "TBA"}];
movies.forEach(({theatricalrelease}) => console.log(theatricalrelease));
.as-console-wrapper { max-height: 100% !important; top: 0; }
moviesarray, right?var movies =[ "Black Panther" :{...}, "Infinity War":{...}...]?}for first for loop, then give a try by replacingconsole.log(property);withconsole.log(movies[i][property]['theatricalrelease']);[{title:"Black Panther",...},{title:"Infinity War",...}]if you want an array of objects. What you had is fine, it's just not an array.