Suppose I have a list of student information as follows:
1 2 3 4 |
const students: Student[] = [ { id: "1", name: "Khanh" }, { id: "2", name: "Quan" }, ]; |
with the Student class with the following content:
1 2 3 4 |
interface Student { id: string; name: string; } |
If I now define another class StudentInfo that also contains student information with more information about the class as follows:
1 2 3 4 5 |
interface StudentInfo { id: string; studentName: string; className: string; } |
To convert the list of Student objects above into a list of StudentInfo objects, you can use the map() method as follows:
1 2 3 4 5 6 7 |
const studentInfos: StudentInfo[] = students.map((student) => { return { id: student.id, studentName: student.name, className: "A", }; }); |
The map() method will process each element of the array. In the above example, for each element of the “students” array, we will initialize a StudentInfo object with properties whose values are derived from the Student object. Here, I am assigning the default class information to “A”, depending on your needs, you can write the code accordingly.
The result when I run this example is as follows: