繁体   English   中英

Javascript从对象数组中的对象数组获取对象数组

[英]Javascript get array of objects from array of objects in array of objects

我有一个带有注册的数组,在这个数组中是一个学生数组。
现在,我需要一个只有firstName,lastName和email的所有学生组成的数组。

注册数组

[
  0: {
    date: "2019-04-08T13:51:10.215Z"
    onlyVAT: false,
    students: [
      0: {
        email: "ben@test.be",
        firstName: "Bennn",
        lastName: "test",
        phone: "0898989"
        ...
      }
    ]
  }
]

到目前为止,我有:

 this.registrations.map(
    registration => registration.students.map(
        student => { return {
          firstName: student.firstName,
          lastName: student.lastName,
          email: student.email
          }}
      )
    );

但这会返回一个数组数组

0: [
  0: {firstName: "Bennn", lastName: "test", email: "ben@test.be"},
  1: ...
]

我想要的是(部分)学生对象的数组

[
  0: {firstName: "Bennn", lastName: "test", email: "ben@test.be"},
  1: ...
]

当然,我可以循环并推送到一个新数组,但这不是我想要的

使用flat()flatMap() 例:

  const newArr = registrations.map(
    registration => registration.students.map(
      student => { return {
        firstName: student.firstName,
        lastName: student.lastName,
        email: student.email
      }}
    )
  ).flat();

  console.log(newArr);

只需使用flatMap

this.registrations.flatMap(...);

或使用reduce

this.registrations.map(...).reduce((a, c) => [...a, c], []);

这是带有两个Array.reduce()函数和Object.values()的解决方案,这将确保输出仅包含唯一的电子邮件(在示例输入中,我有两封相同的电子邮件ben4@test.be ):

 const registrations = [ { date: '2019-04-08T13:51:10.215Z', onlyVAT: false, students: [ { email: 'ben@test.be', firstName: 'Bennn', lastName: 'test', phone: '0898989' }, { email: 'ben2@test.be', firstName: 'Bennn2', lastName: 'test2', phone: '0898989' } ] }, { date: '2019-05-08T13:51:10.215Z', onlyVAT: false, students: [ { email: 'ben3@test.be', firstName: 'Bennn3', lastName: 'test3', phone: '0898989' }, { email: 'ben4@test.be', firstName: 'Bennn4', lastName: 'test4', phone: '0898989' }, { email: 'ben4@test.be', firstName: 'Bennn4', lastName: 'test4', phone: '0898989' } ] } ]; const result = registrations.reduce((res, {students}) => ({ ...res, ...students.reduce((res2, {email, firstName, lastName}) => ({ ...res2, [email]: {email, firstName, lastName} }), {}) }), {}); console.log(Object.values(result)); 

由于students是数组中对象内部的字段,因此以这种形式获得结果。

您可以简单地将concat... spread运算符组合使用在从地图获得的结果上,以获得最终的学生数组。

const studentsMapped = this.registrations.map(
    registration => registration.students.map(
        student => { return {
            firstName: student.firstName,
            lastName: student.lastName,
            email: student.email
       }}
    )
);

const students = [].concat(...studentsMapped);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM