[英]Add a property from one object, as a property in another object
我正在嘗試用下面的代碼練習兩個概念; 數組filter()
function,並使用它從一個 object 中獲取屬性,並將其作為屬性添加到另一個中。
我做了兩個對象, 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}))
}
));
您是否嘗試返回一個新數組而不是更改原始教師數組,看看這個例子:
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) => teacher.name === student.teacher); teacher.students = filterStudents.reduce((acc, student) => { acc.push(student.name) return acc; }, []) return teacher }); console.log(assignStudentsToTeachers);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.