Below is a JSON object that needs to be parsed to extract values only from the last children available in the list for each object:
{
"projectInfo": {
"cabinetInfo": [
{
"nodeName": "EAST",
"boxName": "EAST-Box",
"children": [
{
"nodeName": "Street-3",
"smsName": "smsname",
"boxserilaNumber": 4004342423
},
{
"nodeName": "Street-2",
"smsName": "smsname",
"boxserilaNumber": 4004342423
},
{
"nodeName": "Street-1",
"smsName": "smsname",
"boxserilaNumber": 4004342423
}
]
},
{
"nodeName": "NORTH",
"boxName": "NORTH-Box",
"children": [
{
"nodeName": "ZONE1",
"boxName": "ZONE1-Box",
"children": [
{
"nodeName": "AREA",
"boxName": "AREA-Box",
"children": [
{
"nodeName": "Street-3",
"smsName": "smsname",
"boxserilaNumber": 4004342423
},
{
"nodeName": "Street-2",
"smsName": "smsname",
"boxserilaNumber": 4004342423
},
{
"nodeName": "Street-1",
"smsName": "smsname",
"boxserilaNumber": 4004342423
}
]
}
]
}
]
},
{
"nodeName": "SOUTH",
"boxName": "SOUTH-Box",
"children": [
{
"nodeName": "ZONE1",
"boxName": "ZONE1-Box",
"children": [
{
"nodeName": "SOCIETY",
"boxName": "SOCIETY-Box",
"children": [
{
"nodeName": "AREA",
"boxName": "AREA-Box",
"children": [
{
"nodeName": "Street-4",
"smsName": "smsname",
"boxserilaNumber": 4004342423
},
{
"nodeName": "Street-3",
"smsName": "smsname",
"boxserilaNumber": 4004342423
},
{
"nodeName": "Street-2",
"smsName": "smsname",
"boxserilaNumber": 4004342423
},
{
"nodeName": "Street-1",
"smsName": "smsname",
"boxserilaNumber": 4004342423
}
]
}
]
}
]
}
]
}
]
}
}
I attempted to code the function to extract the values but it is only retrieving 3 box serial numbers instead of 9. As a newcomer to JavaScript, I am struggling to identify the mistake in my code. I believe the issue lies in the renderCabinetInfoList method where I am recursively calling to reach the bottom of the list with children.
function renderCabinetInfo(nodeTree)
{
var cabinetLists = nodeTree.projectInfo.cabinetInfo;
for(var j=0;j<cabinetLists.length;j++)
{
var cabinetList = cabinetLists[j].children;
var cabinetInfoTags = renderCabinetInfoList(cabinetList);
var cTable=document.getElementById('cabinetInfoTable');
for(var i=0;i<cabinetInfoTags.length;i++)
{
console.log(cabinetInfoTags[i].boxserilaNumber);
}
}
};
function renderCabinetInfoList(cabinetList)
{
for(var i=0;i<cabinetList.length;i++)
{
var cabi = cabinetList[i];
if(haveChildren(cabi)) {
renderCabinetInfoList(cabi.children);
}
else
{
break;
}
}
return cabinetList=cabinetList;
}
function haveChildren(cabi)
{
if (null != cabi.children && cabi.children.length>0) {
return true;
}
return false;
}