假设以下是我们的嵌套对象-
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