Hey there! I'm currently working with Angular 4 and I have a piece of code that parses data from an API into a TypeScript array of rows. It's important to note that the code functions properly if elements like 'item.tceCampRun' and 'item.tceCommTreeDetail' are present.
However, when one of these elements, such as 'item.tceCommTreeDetail', is missing, I encounter the following error: TypeError: Cannot read property 'map' of undefined.
I was wondering what would be the most effective approach to handle a nested object in this situation?
private handleGetCamp(data: Response) {
if (data.status === 200) {
// this.tceCamp = data.json();
// this.firstTceCamp = this.tceCamp[0];
let other = []; // your other array...
let j = 1;
let run = 999000;
let runheader = true;
let runheaderid = 1;
data.json().map(item => {
j++;
runheader = true;
return {
id: j,
rowtype: 'camp',
expanded: false,
cells: [{ cid: 1, text: item.name }, { cid: 2, text: item.dailyStartTime }, { cid: 3, text: item.dailyEndTime }, { cid: 4, text: item.scriptId }, { cid: 14 }],
rows:[{
id: run++,
pid: j,
header: true,
rowtype: 'run',
expanded: false,
cells: [{cid: 1, text: 'Runs', header: false},
{cid: 2, text: 'Created', header: true},
{cid: 3, text: 'Modified', header: true},
{cid: 4, text: 'Camp', header: true},
{cid: 12, text: ' ', header: true},
{cid: 13, text: ' ', header: true}],
rows:
item.tceCampRun.map(item2 => {
return {
id: run++,
mypid: runheaderid,
pid: runheaderid,
rowtype: 'run',
expanded: false,
cells: [{cid: 1, text: item2.name}, {cid: 2, text: 'c 2'}, {cid: 3, text: 'c 3'}, {
cid: 4,
text: item2.id
}, {cid: 14}]
}
})
},
{
id: run++,
pid: j,
header: true,
expanded: false,
rowtype: 'InteractiveScript',
cells: [{ cid: 1, text: 'Interactive Script', header: false },
{ cid: 2, text: 'Response', header: true },
{ cid: 3, text: 'Action', header: true },
{ cid: 4, text: 'Action Value', header: true },
{ cid: 12, header: true },
{ cid: 13, header: true }],
rows:
item.tceCommTreeDetail.map(item3 => {
return {
id: run++,
mypid: runheaderid,
pid: runheaderid,
rowtype: 'run',
expanded: false,
cells: [{cid: 1, text: item3.name}, {cid: 2, text: 'c 2'}, {cid: 3, text: 'c 3'}, {
cid: 4,
text: item3.id
}, {cid: 14}]
}
})
}
]
}
}).forEach(item => other.push(item));
The format of the nested rows should resemble this image: https://i.stack.imgur.com/yJXez.png