如何使用 JavaScript map() 方法訪問巢狀物件?
假設我們有如下巢狀物件 −
var details = [ { id:"101", firstName:"John", lastName:"Smith", age:25, countryName:"US", subjectDetails: { subjectId:"Java-101", subjectName:"Introduction to Java" }, }, { "uniqueId": "details_10001" } ]
使用 map() 和 typeOf 訪問巢狀物件。以下為程式碼 −
樣例
var details = [ { id:"101", firstName:"John", lastName:"Smith", age:25, countryName:"US", subjectDetails: { subjectId:"Java-101", subjectName:"Introduction to Java" }, }, { "uniqueId": "details_10001" } ] details.map((nestedObject)=>{ if (typeof nestedObject.subjectDetails != 'undefined') console.log("The subject Name="+nestedObject.subjectDetails.subjectName); })
要執行以上程式,需要使用以下命令 −
node fileName.js.
此處,我的檔名是 demo119.js。
輸出
將產生以下輸出 −
PS C:\Users\Amit\JavaScript-code> node demo119.js The subject Name=Introduction to Java
廣告