ใช้ map() วนอาเรย์ ตรวจสอบ typeof nestedObject !== 'undefined' ก่อนเข้าถึง Property ซ้อน
ตัวอย่างโค้ด
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 (เช่น node demo119.js)
ผลลัพธ์
The subject Name=Introduction to Java