gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:13:35 25 4
gpt4 key购买 nike

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

注册数组

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

关于Javascript 从对象数组中的对象数组获取对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56787990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com