Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a an Object of an Object Angular 4

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

like image 504
CruelEngine Avatar asked Sep 01 '17 06:09

CruelEngine


2 Answers

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
}
like image 175
Arg0n Avatar answered Oct 19 '22 23:10

Arg0n


In the comment OP has asked for a map with studentID as key and StudentDetails as the value.

Following code can help you but as the Question itself is not clear please do not down vote in the impulse.

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 )

like image 23
KIA Avatar answered Oct 19 '22 22:10

KIA