Search code examples
javascriptarraysangularnested-loops

Angular 9 : Rearrange array object into nested array


I'm trying to re-arrange:


[
  {
    "id": 5,
    "levelName": "Level 1"
  },
  {
    "id": 6,
    "levelName": "Level 2"
  },
  {
    "id": 7,
    "levelName": "Level 3"
  }
]

To:

[
  {
    "id": 5,
    "levelName": "Level 1",
    "level": [
      {
        "id": 6,
        "levelName": "Level 2",
        "level": [
          {
            "id": 6,
            "levelName": "Level 2",
            "level": []
          }
        ]
      }
    ]
  }
]

I am trying to make tree structured UI layout. but I'm wondering how to achieve converting the data part. Wishful thinking perhaps, but is there an easier way than looping within loops!?


Solution

  • You can reduce the array using an object as a map for the levels.

    const arr = [ { "id": 5, "levelName": "Level 1" }, { "id": 6, "levelName": "Level 2" }, { "id": 7, "levelName": "Level 3" } ];
    const res = arr.reduce((acc,obj)=>{
      let level = +obj.levelName.slice(obj.levelName.indexOf(' ') + 1);
      (acc[level] = acc[level] || []).push(obj);
      acc[level + 1] = acc[level + 1] || (obj['level'] = []);
      return acc;
    }, {})[1];
    console.log(res);