Giả sử sau đây là các đối tượng lồng nhau của chúng ta -
var details = [
{
id:"101",
firstName:"John",
lastName:"Smith",
age:25,
countryName:"US",
subjectDetails: {
subjectId:"Java-101",
subjectName:"Introduction to Java"
},
},
{
"uniqueId": "details_10001"
}
] Sử dụng map () cùng với typeOf để truy cập các đối tượng lồng nhau. Sau đây là mã -
Ví dụ
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);
}) Để chạy chương trình trên, bạn cần sử dụng lệnh sau -
node fileName.js.
Đây, tên tệp của tôi là demo119.js.
Đầu ra
Điều này sẽ tạo ra kết quả sau -
PS C:\Users\Amit\JavaScript-code> node demo119.js The subject Name=Introduction to Java