I have a JSON with a format similar to this:
[{
"email": "[email protected]",
"school_id": 1,
"school": "Escuela 1"
}, {
"email": "[email protected]",
"school_id": 1
"school": "Escuela 1"
}, {
"email": "[email protected]",
"school_id": 1
"school": "Escuela 1"
}, {
"email": "[email protected]",
"school_id": 2,
"school": "Escuela 2"
}];
And I would like to create a New JSON that joins the school_id and school properties into a new property called schools which would be an array of[{school_id: number, school: string}]
I would like to make use of functional programming, however, I still can't find the correct way to achieve this:
[{
"email": "[email protected]",
"schools": [{
"school_id": 1,
"school": "Escuela 1"
} {
"school_id": 2,
"school": "Escuela 2"
}
},
{
"email": "[email protected]",
"schools": [{
"school_id": 1,
"school": "Escuela 1"
}]
},
{
"email": "[email protected]",
"schools": [{
"school_id": 1,
"school": "Escuela 1"
}]
}];
So far I have tried this:
let results = [{
"email": "[email protected]",
"school_id": 1,
"school": "Escuela 1"
}, {
"email": "[email protected]",
"school_id": 1,
"school": "Escuela 1"
}, {
"email": "[email protected]",
"school_id": 1,
"school": "Escuela 1"
}, {
"email": "[email protected]",
"school_id": 2,
"school": "Escuela 2"
}];
results.forEach((result, idx) => {
if (results.findIndex(el => el.email === result.email) > idx) {
result.schools.push(results.filter((el, index) => el.email === result.email && index > idx));
delete result.schools.email;
delete result.school_id;
} else {
result.schools = [{
school_id: result.school_id,
school: result.school
}]
delete result.school_id;
delete result.school;
}
});
console.log(results);
console.log(JSON.stringify(results));