简体   繁体   中英

Get object properties for objects in array

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?

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']) } 

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; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM