skip to Main Content
student:any=[{name:'shariful', id:'1',teacherId:'1'},{name:'Hasan', id:'2',teacherId:'2'},{name:'sohag', id:'3',teacherId:'2'}]
teacher:any=[{name:'Robi',id:'1'},{name:'Aktarujaman',id:'2'}]

needResult:any=[{name:'shariful', id:'1',teacherId:1,teacherName:'Robi'},{name:'Hasan', id:'2',teacherId:'2',teacherName:'Aktarujaman'},{name:'sohag', id:'3',teacherId:'1',teacherName:'Robi'}]

I need to join student and teacher . the output is as like as needResult .

Need to join in my angular project

2

Answers


  1. Just map student, and add the teacherName by finding the corresponding teacher in the teacher array:

    let student =[{name:'shariful', id:'1',teacherId:'1'},{name:'Hasan', id:'2',teacherId:'2'},{name:'sohag', id:'3',teacherId:'2'}];
    let teacher=[{name:'Robi',id:'1'},{name:'Aktarujaman',id:'2'}]
    
    let result = student.map(s => {
        return {
            ...s,
            teacherName: teacher.find(t => t.id === s.teacherId).name
        }
    });
    
    console.log(result);
    Login or Signup to reply.
  2. For linear time complexity, you can first create an object (or Map) that associates each teacher id with the teacher name. Then, you can use Array#map to create a new array where the teacher name is added to each element.

    const students = [{name:'shariful', id:'1',teacherId:'1'},{name:'Hasan', id:'2',teacherId:'2'},{name:'sohag', id:'3',teacherId:'2'}];
    const teachers = [{name:'Robi',id:'1'},{name:'Aktarujaman',id:'2'}];
    
    const teacherLookup = Object.fromEntries(teachers.map(t => [t.id, t.name]));
    const res = students.map(o => ({...o, teacherName: teacherLookup[o.teacherId]}));
    console.log(res);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search