Supongamos que tengo dos matrices. El primero tiene detalles del estudiante y el estudiante marca detalles. Ambas matrices tienen la clave común, que es '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 },
];
Quiero fusionar las dos matrices basadas en la clave 'studentId'. He creado una función para fusionar las dos matrices.
const mergeById = (array1, array2) =>
array1.map(itm => ({
...array2.find((item) => (item.studentId === itm.studentId) && item),
...itm
}));
aquí está el código para obtener el resultado final
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}
]