merge two object arrays with Angular 2 and TypeScript?

前端 未结 6 700
长情又很酷
长情又很酷 2020-12-14 05:19

I have gone across the JavaScript questions on this topic, this question is specifically about Angular2 with TypeScript.

What I am trying to do is to concatenate the

6条回答
  •  死守一世寂寞
    2020-12-14 05:59

    Assume i have two arrays. The first one has student details and the student marks details. Both arrays have the common key, that is ‘studentId’

    let studentDetails = [
      { studentId: 1, studentName: 'Sathish', gender: 'Male', age: 15 },
      { studentId: 2, studentName: 'kumar', gender: 'Male', age: 16 },
      { studentId: 3, studentName: 'Roja', gender: 'Female', age: 15 },
      {studentId: 4, studentName: 'Nayanthara', gender: 'Female', age: 16},
    ];
    
    let studentMark = [
      { studentId: 1, mark1: 80, mark2: 90, mark3: 100 },
      { studentId: 2, mark1: 80, mark2: 90, mark3: 100 },
      { studentId: 3, mark1: 80, mark2: 90, mark3: 100 },
      { studentId: 4, mark1: 80, mark2: 90, mark3: 100 },
    ];
    

    I want to merge the two arrays based on the key ‘studentId’. I have created a function to merge the two arrays.

    const mergeById = (array1, array2) =>
        array1.map(itm => ({
          ...array2.find((item) => (item.studentId === itm.studentId) && item),
          ...itm
        }));
    

    here is the code to get the final result

    let result = mergeById(studentDetails, studentMark);

    [
    {"studentId":1,"mark1":80,"mark2":90,"mark3":100,"studentName":"Sathish","gender":"Male","age":15},{"studentId":2,"mark1":80,"mark2":90,"mark3":100,"studentName":"kumar","gender":"Male","age":16},{"studentId":3,"mark1":80,"mark2":90,"mark3":100,"studentName":"Roja","gender":"Female","age":15},{"studentId":4,"mark1":80,"mark2":90,"mark3":100,"studentName":"Nayanthara","gender":"Female","age":16}
    ]
    

提交回复
热议问题