[英]Angular - 7 - How to create object from Response having many fields?
How to map and use piple to create new object in Angular ? 如何在Angular中映射和使用piple创建新对象? Below is the response I am getting from Service. 以下是我从“服务”获得的响应。 I only want studentId, name and Title
field. 我只需要studentId, name and Title
字段。
{
"studentList": [
{
"studentId": "e094208",
"name": "John Doe",
"Title": "Senior Engineering",
"phoneNumbers": [
{
"number": "",
"type": "BUSINESS",
"public": false
},
{
"number": "",
"type": "MOBILE",
"public": false
}
],
"emails": [
{
"email": "john.doe@gmail.com",
"type": "BUSINESS",
"public": false
},
.......
.......
.......
}
}
Here is the my code. 这是我的代码。 How to convert it into Student[]
with three fields? 如何通过三个字段将其转换为Student[]
?
student = Student[];
this.studentService.searchStudent(name).subscribe((response: any) => {
this.studentResponse = response.studentList;
});
Try something like this. 尝试这样的事情。
var studentListParsed = JSON.parse('<YOUR JSON>');
const data: Array<Student> = studentListParsed.studentList.map(student => {
return {
studentId: student.studentId,
name: student.name,
title: student.title
}
});
You can pipe the data and map to the fields you want in the service. 您可以通过管道传输数据并将其映射到服务中所需的字段。 That is how I prefer to do it: 我更喜欢这样做:
EDIT: Some change to the data structure as per your comment. 编辑:根据您的评论对数据结构进行一些更改。
service: 服务:
import { map } from 'rxjs/operators';
// ....
searchStudent(name): Observable<Student[]> {
// your function here to fetch data
.pipe(
map(data => {
return data.peopleList.map(student => {
return <Student>{ eId: student.emplNtId, name: student.name, jobTitle: student.busnTitle }
})
})
)
}
Then in your component just assign the data to your variable: 然后在您的组件中,只需将数据分配给您的变量即可:
this.studentService.searchStudent().subscribe((response: Student[]) => {
this.studentResponse = response;
console.log(this.studentResponse)
});
PS: Also remember to type your data, avoid using any
:) PS:也请记住键入您的数据,避免使用any
:)
You can use map function something like 您可以使用类似的地图功能
this.studentService.searchStudent(name).subscribe((response: any) => {
this.student= response.studentList.map(x =>{
return {studentId :x.studentId ,name : x.name ,title :x.Title } as Student;
});
});
Code Example 代码示例
var resp={ "studentList": [ { "studentId": "e094208", "name": "John Doe", "Title": "Senior Engineering", "phoneNumbers": [ { "number": "", "type": "BUSINESS", "public": false }, { "number": "", "type": "MOBILE", "public": false } ], "emails": [ { "email": "john.doe@gmail.com", "type": "BUSINESS", "public": false }] } ] } var data=resp.studentList.map(x =>{ return {studentId :x.studentId ,name : x.name ,title :x.Title } }); console.log(data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.