Supposons que j'ai deux tableaux. Le premier contient les détails de l'élève et les notes de l'élève. Les deux tableaux ont la clé commune, c'est-à-dire '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 },
];
Je souhaite fusionner les deux tableaux en fonction de la clé «studentId». J'ai créé une fonction pour fusionner les deux tableaux.
const mergeById = (array1, array2) =>
array1.map(itm => ({
...array2.find((item) => (item.studentId === itm.studentId) && item),
...itm
}));
voici le code pour obtenir le résultat 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}
]