首页 > 解决方案 > 将一个对象的属性添加为另一个对象的属性

问题描述

我正在尝试用下面的代码练习两个概念;数组filter()函数,并使用它从一个对象中获取属性,并将其作为属性添加到另一个对象中。

我做了两个对象,teachersstudents。我正在尝试使用过滤器将学生添加到教师中,以便每个教师都有一个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);

标签: javascriptfilter

解决方案


尝试这个:

const a = teachers.map(t=>( 
  {...t, 
   students: students
     .filter(s => s.teacher === t.name)
     .map(s=>({name:s.name})) 
  }
));

推荐阅读