One approach would be to define a class for handling student information in a structured manner. This method offers benefits such as maintaining consistent property names, unlike when adding properties dynamically using methods like data['subject1'] = 'math';
or data.subject1 = math
.
class Student{
public name: string;
public dateOfEntry: string;
public subjects: Array<Subject>;
constructor(name: string, dateOfEntry: string){
this.name = name;
this.dateOfEntry = dateOfEntry;
this.subjects = new Array<Subject>();
}
public addSubject(subject: Subject){
// Only add the subject if it is not already in the list
if(!this.subjects.find(val => val == subject))
this.subjects.push(subject);
}
}
class Subject{
public name: string;
constructor(name: string){
this.name = name;
}
}
When creating a new student instance...
let bob: Student = new Student("bob", new Date().toString());
bob.addSubject(new Subject("Math")); // Adds to the list
bob.addSubject(new Subject("English")); // Adds to the list
bob.addSubject(new Subject("Math")); // Will not add as it already exists