I am attempting to combine related objects within an array of objects based on matching properties in a specific object key "name".
Although I have implemented the following code, unfortunately it did not yield the desired results:
const students = [];
const obj = [{
"name": "A. Nasila",
"adm": "",
"class": "4p",
"mat": "80",
"eng": "",
"kis": ""
},
{
"name": "A. Nasila",
"adm": "4886",
"class": "",
"mat": "",
"eng": "",
"kis": "39"
},
{
"name": "Mtu Bure",
"adm": "",
"class": "3L",
"mat": "",
"eng": "86",
"kis": ""
},
{
"name": "A. Nasila",
"adm": "",
"class": "",
"mat": "",
"eng": "75",
"kis": ""
},
{
"name": "Mtu Bure",
"adm": "9790",
"class": "",
"mat": "77",
"eng": "",
"kis": "76"
}
];
const groupedData = obj.reduce((acc, cur) => {
const name = cur.name;
if (!acc[name]) {
acc[name] = {};
}
for (const key in cur) {
acc[name][key] = cur[key];
}
return acc;
}, {});
const result = Object.values(groupedData);
const jsonObject = JSON.stringify(result);
const div = document.getElementById("students");
const span = document.createElement("span");
span.innerHTML = jsonObject;
div.appendChild(span);
<div id="students">
</div>
Please assist me in achieving the expected output as demonstrated below;
[
{
"name": "A. Nasila",
"adm": "4886",
"class": "4p",
"mat": "80",
"eng": "75",
"kis": "39"
},
{
"name": "Mtu Bure",
"adm": "9790",
"class": "3L",
"mat": "77",
"eng": "86",
"kis": "76"
}
]