I need help iterating through an array of objects with a specific interface structure:
export interface Incident {
ID: string;
userName1?: string;
userName2?: string;
userPhoneNumber?: string;
crashSeverity: number;
crashTime: number;
}
Here is a sample data set:
{
crashID: "CO111111",
userName1: "TEST",
userName2: "NAME2",
userPhoneNumber: "11111",
crashSeverity: 2,
crashTime: 1571566666
},
{
crashID: "12345",
userName1: "TEST",
crashSeverity: 2,
crashTime: 1571566666
}
I want to save this data to a csv file, but I'm struggling with iterating through the entire incident interface for each object and handling missing properties. Is there a way to achieve this?
An example output can be seen here: https://i.sstatic.net/ByAHg.png
This is my current code snippet:
ConvertToCSV(objArray) {
const array =
typeof objArray !== "object" ? JSON.parse(objArray) : objArray;
let str = "";
let header = "";
for (const index in objArray[0]) {
header += index + ";";
}
header = header.slice(0, -1);
// append Label row with line break
str += header + "\r\n";
// loop through every entry
for (let i = 0; i < array.length; i++) {
let line = "";
// loop through every row
for (const firstIndex in array[i]) {
line += array[i][firstIndex] + ";";
}
str += line + "\r\n";
}
return str;
}