I have the following array of objects
[{
"school_id": "s1",
"school_name": "school1",
"district_id": "d1",
"students": [{
"student_id": "1",
"student_name": "tony"
}, {
"student_id": "2",
"student_name": "tom"
}]
}, {
"school_id": "s2",
"school_name": "school2",
"district_id": "d2",
"students": [{
"student_id": "1",
"student_name": "march"
}, {
"student_id": "2",
"student_name": "alex"
}]
}, {
"school_id": "s3",
"school_name": "school3",
"district_id": "d3",
"students": [{
"student_id": "1",
"student_name": "bill"
}, {
"student_id": "2",
"student_name": "bob"
}]
}, {
"school_id": "s4",
"school_name": "school4",
"district_id": "d3",
"students": {
"student_id": "1",
"student_name": "tim"
}
}]
I need to generate new repsonse by combining students belonging to the same school in the sae district as shown below
[{
"district_id": "d1",
"schoolList": [{
"school_id": "s1",
"school_name": "school1",
"studentList": [{
"student_id": "1",
"student_name": "tony"
}, {
"student_id": "2",
"student_name": "tom"
}]
}]
}, {
"district_id": "d2",
"schoolList": [{
"school_id": "s2",
"school_name": "school2",
"studentList": [{
"student_id": "1",
"student_name": "march"
}, {
"student_id": "2",
"student_name": "alex"
}]
}]
}, {
"district_id": "d3",
"schoolList": [{
"school_id": "s3",
"school_name": "school3",
"studentList": [{
"student_id": "1",
"student_name": "bill"
}, {
"student_id": "1",
"student_name": "bill"
}]
}, {
"school_id": "s4",
"school_name": "school4",
"studentList": {
"student_id": "1",
"student_name": "tim"
}
}]
}]
How do I achieve it?
3
Answers
To achieve the desired result of combining students belonging to the same school in the same district, you can use JavaScript to iterate through the original array of objects and create a new response array based on the district and school information. Here’s a step-by-step solution:
You can collect the unique districts ids as keys of a plain object, and associate the result object to each. Upon the first encounter of a district id, create the object for it (with empty
schoolList
array). Add each school to theschoolList
array that corresponds to the district:It is my solution.