[英]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
. 使用普通的JavaScript,我试图访问属性, theatricalrelease
阵列中的所有对象, 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. 如您所见,我试图在另一个对象中使用另一个for循环,因为我希望它能遍历对象的索引名称。 Instead, logging property
gave me the name of each index. 相反,logging property
为我提供了每个索引的名称。 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
. 现在,这将在您的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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.