I am trying to merge related objects in an array of objects based on similar properties in a specific object key "name".
I have tried the following code but did not work:
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>
Help me get the desired output as shown 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"
}
]
2
Answers
This should work
A little explanation of what’s going on
First off, I used the reduce method to iterate through the array of objects (obj) and group them by the
name
property into thegroupedData
object.If the
name
property is encountered for the first time, I then create a new object for it. If it has already been encountered, we merge the current object’s properties into the existing object.I then converted the
groupedData
object into an array of values usingObject.values
method.you can also use ??= operator ( Nullish coalescing assignment )