javascript - 将一个对象的属性添加为另一个对象的属性
问题描述
我正在尝试用下面的代码练习两个概念;数组filter()
函数,并使用它从一个对象中获取属性,并将其作为属性添加到另一个对象中。
我做了两个对象,teachers
和students
。我正在尝试使用过滤器将学生添加到教师中,以便每个教师都有一个teacher.student
属性。
其中一位老师有两个学生,所以理想情况下,teacher.student 是一组对象。
基本上我正在尝试转向,例如:
teachers[2] = {name: 'Melissa', class: 'English'}
进入
teachers[2] = {name: 'Melissa', class: 'English', students:[{name:'Mike'},{name:'Janet'}]}
在我下面的解决方案中,teachers[2]
只添加了珍妮特,但忽略了迈克。
如果这些建议可以是对我所拥有的东西的调整(以便我可以按照自己的节奏学习),我将不胜感激,并且如果可能的话,还有一个更简单/更短的辅助解决方案,这样我就可以了解更有效的方法接近这个。我想这可以在没有过滤器的情况下实现,但我只需要使用它来适应使用它。
提前致谢!
const teachers = [
{name: 'James', class: 'Computer Science'},
{name: 'Thomas', class: 'Biology'},
{name: 'Melissa', class: 'English'}
];
const students = [
{name: 'Mike', teacher: 'Melissa'},
{name: 'Janet', teacher: 'Melissa'},
{name: 'Elliot', teacher: 'Thomas'},
{name: 'Gabe', teacher: 'James'},
]
const assignStudentsToTeachers = teachers.map((teacher) => {
const filterStudents = students.filter((student) => {
return teacher.name === student.teacher;
});
const filterStudentNames = filterStudents.map((student) => {
for(let property in student){
if(property === 'name'){
teacher.students = [{'name': student[property]}];
}
}
});
});
console.log(teachers);
解决方案
尝试这个:
const a = teachers.map(t=>(
{...t,
students: students
.filter(s => s.teacher === t.name)
.map(s=>({name:s.name}))
}
));
推荐阅读
- azure-devops - 如何比较 VSTS 中的两个非顺序拉取请求更新?
- android - Android anjlab 应用内计费 - 收费
- php - 通过php在bigquery中执行插入操作
- asp.net - 解码请求中发送的 __VIEWSTATE
- javascript - 在Angularjs运行块中等待异步javascript
- javascript - 页面加载时的 HtmlUnit JavaScript 问题 - 找不到函数
- regex - [Regex]::Replace() 和 -replace 有什么区别?
- symfony-3.4 - 如何在我的项目中独立使用事件命令 Symfony?
- node.js - 调试我的打字稿文件时出错:-> 附加调试器。等待调试器断开连接
- ruby-on-rails - 如何检查 ruby on rails 中的表单完整性?