Angular-7-如何从具有多个字段的响应创建对象?

Angular-7-如何从具有多个字段的响应创建对象?,angular,angular7,Angular,Angular7,如何映射和使用piple在Angular中创建新对象?以下是我从服务部得到的回复。我只需要studentId、姓名和职称字段 { "studentList": [ { "studentId": "e094208", "name": "John Doe", "Title": "Senior Engineering", "phoneNumbers": [ { "number": "",

如何映射和使用piple在Angular中创建新对象?以下是我从服务部得到的回复。我只需要
studentId、姓名和职称
字段

{
  "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
        },
        .......
        .......
        .......
    }
}
这是我的密码。如何将其转换为带有三个字段的
Student[]

student = Student[];
this.studentService.searchStudent(name).subscribe((response: any) => {
    this.studentResponse = response.studentList;
});
你可以用像

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;
});

});
代码示例

var resp={
“学生名单”:[
{
“学生ID”:“e094208”,
“姓名”:“约翰·多伊”,
“职称”:“高级工程”,
“电话号码”:[
{
“编号”:“编号”,
“类型”:“业务”,
“公众”:虚假
},
{
“编号”:“编号”,
“类型”:“移动”,
“公众”:虚假
}
],
“电子邮件”:[
{
“电子邮件”:“约翰。doe@gmail.com",
“类型”:“业务”,
“公众”:虚假
}]
}
]
}
var data=resp.studentList.map(x=>{
返回{studentId:x.studentId,name:x.name,title:x.title}
});

console.log(数据)
试试这样的方法

var studentListParsed = JSON.parse('<YOUR JSON>');

const data: Array<Student> = studentListParsed.studentList.map(student => {
return {
    studentId: student.studentId,
    name: student.name,
    title: student.title 
    }
});
var studentListParsed=JSON.parse(“”);
常量数据:Array=studentListParsed.studentList.map(student=>{
返回{
学生ID:student.studentId,
姓名:student.name,
头衔:学生
}
});

您可以通过管道传输数据并映射到服务中所需的字段。我更喜欢这样做:

编辑:根据您的评论对数据结构进行一些更改

服务:


从'rxjs/operators'导入{map};
// ....
搜索学生(姓名):可观察{
//您的函数在此获取数据
.烟斗(
地图(数据=>{
返回data.peopleList.map(student=>{
return{eId:student.emplNtId,name:student.name,jobTitle:student.buntitle}
})
})
)
}
然后在组件中,只需将数据分配给变量:

this.studentService.searchStudent().subscribe((响应:Student[])=>{
this.studentResponse=响应;
console.log(this.studentResponse)
});


PS:也请记住键入数据,避免使用
任何
:)

@PAA您可以在这里发布什么不起作用。说不起作用无助于理解实际问题,或者请添加您想要获得的实际输出。我想在
学生[]
中填充所有内容,var将没有帮助。学生模型有ID、FullName和JobTitle,我想在那里映射要创建的值array@PAA您可以将
{studentId:x.studentId,name:x.name,title:x.title}
转换为
student
查看更新的ans。如果您仍然遇到问题,请在此处发布错误。此处的地图是什么?您指的是哪一个地图?一个是rxjs
map
第二个是JS Array.prototype
map
您能分享导入语句吗?
从“rxjs/operators”导入{map}这仍然对我不起作用。这是我的实际代码
searchPeople(searchword:string):可观察的{returnthis.http.get(URL+searchword).pipe(map(data=>{return{eId:data.emplNtId,name:data.name,jobTitle:data.busintitle});}
为什么在这里使用var?我需要一批学生