繁体   English   中英

获取数组中对象的对象属性

[英]Get object properties for objects in array

使用普通的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); } } } } 

如您所见,我试图在另一个对象中使用另一个for循环,因为我希望它能遍历对象的索引名称。 相反,logging property为我提供了每个索引的名称。 如何访问每部电影的剧场版?

问题是您在代码底部有一个包含一个对象的数组和一个额外的}括号。 我对您的阵列做了一些更改,以达到您的预期。 现在,这将在您的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']) } 

根据您的方法: 仅一个元素

 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.

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