Reputation: 2841
I have defined an interface :
export interface Student {
name : String;
section:String;
phoneNumber:String;
}
i want to create an Object of an Object of type Student with studentId
as key . i.e
studentDetails[studentId]
should be of type Student;
studentDetails[studentId] : Student = [];
How can i implement this using inteface ?
Thanks in advance
Upvotes: 16
Views: 176485
Reputation: 192
First Add a studetId to the interface :
export interface Student {
name : String;
section:String;
phoneNumber:String;
studentID : number;
}
Then create a map of studentId with the student detail
students : Student[];
student1 : Student;
var studentMap = new Map();
this.students = [
{name : "abc", section :'A', phoneNumber : '123',studentID : 101 },
{name : "xyz", section :'B', phoneNumber : '456',studentID : 102 },
{name : "mno", section :'C', phoneNumber : '789',studentID : 103 },
];
for (var item of this.students){
studentMap.set (item.studentID ,item);
}
this.student1 = studentMap.get(101);
Please see this (Plunkr I have created )
Upvotes: 2
Reputation: 8423
You can define another interface for StudentDetails
like this:
export interface Student {
name: string;
section: string;
phoneNumber: string;
}
export interface StudentDetails {
[key: number]: Student; //Or string instead of number
}
And use it like this:
//Valid
let studentDetails: StudentDetails = {
1: {
name: 'Test Person1',
section: 'Section 1',
phoneNumber: '12345678'
}
};
//Valid
studentDetails[2] = {
name: 'Test Person 2',
section: 'Section 2',
phoneNumber: '87654321'
};
//Invalid (properties in UpperCase)
studentDetails[3] = {
Name: 'Test Person 3',
Section: 'Section 3',
PhoneNumber: '52376724'
};
//Valid
let student: Student = studentDetails[2];
UPDATE
From your comment to my answer, I assume you want something like this instead:
export interface Student {
id: number; // Added
name: string;
section: string;
phoneNumber: string;
}
export interface StudentMap {
[key: number]: Student;
}
let studentMap: StudentMap = {};
let studentDetails: Student[] = [
{
id: 56,
name: 'Test Person1',
section: 'Section 1',
phoneNumber: '12345678'
},
{
id: 175,
name: 'Test Person3',
section: 'Section 3',
phoneNumber: '521398763'
}
];
studentDetails.forEach((s: Student) => {
studentMap[s.id] = s;
});
for (let i = 0; i < studentDetails.length; i++) {
console.log(studentMap[studentDetails[i].id].name); // Test Person1, Test Person 3
}
Upvotes: 20