簡體   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