I am getting data from a relational database having joined 3 tables:
var btnObj2 = [
{sect_id: 1, sect_title: 'Navigation', subsect_id: 1, subsect_title:'Übersicht', btn_id: 1, btn_title: 'Inhaltsverzeichnis'},
{sect_id: 1, sect_title: 'Navigation', subsect_id: 1, subsect_title: 'Übersicht', btn_id: 2, btn_title: 'Stichwortverzeichnis'},
{sect_id: 1, sect_title: 'Navigation', subsect_id: 2, subsect_title: 'Praxisphasen', btn_id: 3, btn_title: 'Trainingserfolg'},
{sect_id: 1, sect_title: 'Navigation', subsect_id: 2, subsect_title: 'Praxisphasen', btn_id: 4, btn_title: 'Trainingsablauf'},
{sect_id: 2, sect_title: 'Modul 1', subsect_id: 3, subsect_title: 'Mentor-Gespräche', btn_id: 5, btn_title: 'Lebenszeit'},
{sect_id: 2, sect_title: 'Modul 1', subsect_id: 3, subsect_title: 'Mentor-Gespräche', btn_id: 6, btn_title: 'Lebensplanung'},
{sect_id: 2, sect_title: 'Modul 1', subsect_id: 4, subsect_title: 'Just do it', btn_id: 7, btn_title: 'Vertrauen'},
{sect_id: 2, sect_title: 'Modul 1', subsect_id: 4, subsect_title: 'Just do it', btn_id: 8, btn_title: 'Verantwortung'}
];
This data must be restructured so that each section contains its subsections and each sub-section contains its subsub-subsections (subsub-subsections are the buttons in the code snippet above). The data from the database is already returned in the correct order according to sections, sub-sections, subsub-sections.
The output must be as below:
var result = [
{
sect_id: 1,
sect_title: 'Navigation',
subsect: [
{
subsect_id: 1,
subsect_title: 'Übersicht',
buttons: [
{
btn_id: 1,
btn_title: 'Verantwortung'
},
{
btn_id: 2,
btn_title: 'Vertrauen'
}
]
},
{
subsect_id: 2,
subsect_title: 'Praxisphasen',
buttons: [
{
btn_id: 3,
btn_title: 'Trainingserfolg'
},
{
btn_id: 4,
btn_title: 'Trainingsablauf'
}
]
}
]
},
sect_id: 2,
sect_title: 'Module 1',
//.....
];
Here is how I would do it in a PHP-way:
function prepareBtns(arr) {
var sectId, subsectId = ''
var newArr = []
arr.forEach((item) => {
if(sectId !== item.sect_id){
sectId = item.sect_id
}
if(subsectId !== item.subsect_id){
subsectId = item.subsect_id
}
//In PHP the following line does the Job
newArr[sectId][subsectId][] = item
})
return newArr
}
This is one of my JS trials. This one resulted in empty slots:
function prepareBtnsXY(arr) {
var newArr = [];
arr.forEach((item) => {
if (!newArr[item.sect_id]) {
var objToPush = {
sectId: item.sect_id,
sectName: item.sect_title,
subsect: []
};
newArr[item.sect_id] = objToPush;
}
if (!newArr[item.sect_id].subsect[item.subsect_id]) {
var subObjToPush = {
subsectId: item.subsect_id,
subsectName: item.subsect_title,
buttons: []
};
newArr[item.sect_id].subsect[item.subsect_id] = subObjToPush;
}
if (!newArr[item.sect_id].subsect[item.subsect_id].buttons[item.btn_id]) {
var btnObjToPush = {
btnId: item.btn_id,
btnName: item.btn_title
};
newArr[item.sect_id].subsect[item.subsect_id].buttons[item.btn_id] = btnObjToPush;
}
});
return newArr
}