I’m practicing array and objects, though I’m still confusing about making nested objects and arrays.
So i have this type of array and i want to make it nested but i’m having a hard time to do it. I don’t know if it is possible.
const data = [
{
"Date":"3/24/23",
"Course":"BASIC ENGLISH",
"Examiner":"Juan Ponce",
"Participants":"Nardo Putik",
"Examiner Approach":"3",
"Clear explanation of topics discussed":"3",
"Well organized activity from start to finish":"3"
},
{
"Date":"3/24/23",
"Course":"BASIC ENGLISH",
"Examiner":"Juan Ponce",
"Participants":"Cardo Martinez",
"Examiner Approach":"3",
"Clear explanation of topics discussed":"3",
"Well organized activity from start to finish":"3"
},
{
"Date":"3/24/23",
"Course":"BASIC ENGLISH",
"Examiner":"Juan Ponce",
"Participants":"Ippo Kazuya",
"Examiner Approach":"3",
"Clear explanation of topics discussed":"3",
"Well organized activity from start to finish":"3"
}
]
console.log(data);
Expected Output :
const data =
{
"Date" : "3/24/23",
"Course" : "BASIC ENGLISH",
"Examiner" : "Juan Ponce",
"Details" :
[{
"Participants" : "Ippo Kazuya",
"Examiner Approach" : "3",
"Clear explanation of topics discussed" : "3",
"Well organized activity from start to finish" : "3"
},
{
"Participants" : "Cardo Martinez",
"Examiner Approach" : "3",
"Clear explanation of topics discussed" : "3",
"Well organized activity from start to finish" : "3"
},
{
"Participants" : "Nardo Putik",
"Examiner Approach": "3",
"Clear explanation of topics discussed" : "3",
"Well organized activity from start to finish" : "3"
}]
}
2
Answers
I believe that kind of data restructuring is not suggestable in real time as we are not sure that the values of Date, Course and Examiner fields are same for all the objects in the array.
Suggested approach is to group based on a particular property of objects so that the output can be an object with grouped values as keys.
Here’s an approach that uses
reduce()
. The basic idea is to build up a new output array. For every element in the input array, we’ll see if there’s already a matching element in the output array. If there is, we just add to itsDetails
. If not, we create a new element in the output array.Note the use of destructuring to capture the
...rest
of the object properties so they can be easily be added to theDetails
array.Complete snippet: