0

I have the below array

[
 {
   "exam" : "1",
   "class": "1A1",
   "rooms": "245",
   "teachers": "A"
 },
 {
   "exam" : "1",
   "class": "1A2",
   "rooms": "685",
   "teachers": "B"
 },
 {
   "exam" : "2",
   "class": "1EM1",
   "rooms": "630",
   "teachers": "C"
 }
]

How can i convert it in this format ? i tried with groupBy from lodash but i don't get a good result.

[
 {
   "exam" : "1",
   "classes": [
     {
       "class": "1A1",
       "rooms": "245",
       "teachers": "A"
     },
     {
       "class": "1A2",
       "rooms": "685",
       "teachers": "B"
     }
   ]
 },
 {
   "exam" : "2",
   "classes": [
     {
       "class": "1EM1",
       "rooms": "630",
       "teachers": "C"
     }
   ]
 } 
]
0

1 Answer 1

1
var data = [
 {
   "exam" : "1",
   "class": "1A1",
   "rooms": "245",
   "teachers": "A"
 },
 {
   "exam" : "1",
   "class": "1A2",
   "rooms": "685",
   "teachers": "B"
 },
 {
   "exam" : "2",
   "class": "1EM1",
   "rooms": "630",
   "teachers": "C"
 }
];

// Take a blank object as accumuator and add various class objects grouped by examId.
const classDataByExams = data.reduce((acc, x) => {
    // Split object with exam key and the remaining keys on data object.
    const {exam, ...classData} = x;
    // Add the examId in accumuator if not present and then push the classData from above.
    (acc[x.exam] = acc[x.exam] || []).push(classData);
    return acc;
}, {});

// Convert the object to the array format.
console.log(Object.keys(classDataByExams).map(x => ({'exam': x, 'classes': classDataByExams[x]})));

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.