map

  1. const courses = [

  2.     { name: "HTML", levels: ["L1", "L2"] },

  3.     { name: "CSS", levels: ["L1", "L2"] },

  4.     { name: "JS", levels: ["L2", "L3", "M1"] }

  5. ]


  6. const levels = new Set(courses.reduce((acc, { levels: levels }) => ([...acc, ...levels]), []));


  7. const programme = courses.reduce((a, { levels: levels, name }) => {

  8.     for (let level of levels) {

  9.         if (!a[level]) a[level] = [];

  10.         a[level].push(name);

  11.     }

  12.     return a;

  13. }, {});



  14. const menu = Object.entries(programme).map(([level, courses]) => {

  15.     return {

  16.         title: level,

  17.         subnav: courses.map((course) => {

  18.             return { title: course }

  19.         })

  20.     }

  21. })


  22. 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"}]}
]