I have a marks
array containing objects with id
and marks
properties. I also have a user
array containing objects with id
, name
, grade
& result
properties.
var marks = [
{ id: '1', marks: 70 },
{ id: '2', marks: 40 },
{ id: '3', marks: 95 },
{ id: '4', marks: 50 },
];
var user = [
{ id: '1', name: 'sam', grade: 1, result: 'Pass' },
{ id: '2', name: 'peter', grade: 2, result: 'Pass' },
{ id: '5', name: 'John', grade: 1, result: 'Fail' },
{ id: '6', name: 'anna', grade: 3, result: 'Fail' },
];
I want to combine the 2 array objects and generate the following result. If a match for id is found,we need to combine the objects else place null for non-existent properties in both the arrays
var result = [
{ id: '1', marks: 70, name: 'sam', grade: 1, result: 'Pass' },
{ id: '2', marks: 40, name: 'peter', grade: 2, result: 'Pass' },
{ id: '3', marks: 95, name: null, grade: null, result: null },
{ id: '4', marks: 50, name: null, grade: null, result: null },
{ id: '5', marks: null, name: 'John', grade: 1, result: 'Fail' },
{ id: '6', marks: null, name: 'anna', grade: 3, result: 'Fail' },
];
I have tried the following piece of code but it doesn’t generate the desired result. It generates values based only on the first array
marks.forEach((item) => map.set(item.id, item));
user.forEach((item) => map.set(item.id, { ...map.get(item.id), ...item }));
const mergedArr = Array.from(map.values());
Can a workaround for this be suugested?