Załóżmy, że mam dwie tablice. Pierwsza zawiera dane ucznia, a uczeń ocenia szczegóły. Obie tablice mają wspólny klucz, czyli „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 },
];
Chcę połączyć dwie tablice na podstawie klucza „studentId”. Stworzyłem funkcję do scalania dwóch tablic.
const mergeById = (array1, array2) =>
array1.map(itm => ({
...array2.find((item) => (item.studentId === itm.studentId) && item),
...itm
}));
oto kod, aby uzyskać wynik końcowy
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}
]