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

时间:2019-06-27 09:27:15

标签: javascript arrays object ecmascript-6

我有一个注册数组,在这个数组中是一个学生数组。
现在,我想要一个只有名字,姓氏和电子邮件的所有学生的数组。

注册数组

[
  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: ...
]

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

4 个答案:

答案 0 :(得分:2)

使用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);

答案 1 :(得分:1)

只需使用flatMap

this.registrations.flatMap(...);

或使用reduce

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

答案 2 :(得分:1)

这是一个具有两个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));

答案 3 :(得分:0)

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

您可以简单地将...const studentsMapped = this.registrations.map( registration => registration.students.map( student => { return { firstName: student.firstName, lastName: student.lastName, email: student.email }} ) ); const students = [].concat(...studentsMapped); 散布运算符的组合应用于从地图获得的结果,以获得最终的学生数组。

*