const courses = [
{ name: "HTML", levels: ["L1", "L2"] },
{ name: "CSS", levels: ["L1", "L2"] },
{ name: "JS", levels: ["L2", "L3", "M1"] }
]
const levels = new Set(courses.reduce((acc, { levels: levels }) => ([...acc, ...levels]), []));
const programme = courses.reduce((a, { levels: levels, name }) => {
for (let level of levels) {
if (!a[level]) a[level] = [];
a[level].push(name);
}
return a;
}, {});
const menu = Object.entries(programme).map(([level, courses]) => {
return {
title: level,
subnav: courses.map((course) => {
return { title: course }
})
}
})
console.dir(JSON.stringify(menu));
Affiche.
[
{"title":"L1","subnav":[{"title":"HTML"},{"title":"CSS"}]}
,{"title":"L2","subnav":[{"title":"HTML"},{"title":"CSS"},{"title":"JS"}]}
,{"title":"L3","subnav":[{"title":"JS"}]}
,{"title":"M1","subnav":[{"title":"JS"}]}
]