Object with rows to nested object : **Before**

 This is an object with multiple rows:

      {
      "functions": [
        {
          "package_id": "2",
          "module_id": "2",
          "data_id": "2"
        },
        {
          "package_id": "1",
          "module_id": "1",
          "data_id": "2"
        },
        {
          "package_id": "2",
          "module_id": "3",
          "data_id": "3"
        }
      ]
    }

**Desired result**

I want this to return into a "nested" Object like below, without duplicates: 

    {
      "packages": [
        {
          "package_id": "2",
          "modules": [
            {
              "module_id": "2",
              "data": [
                {
                  "data_id": "2"
                }
              ]
            },
            {
              "module_id": "3",
              "data": [
                {
                  "data_id": "3"
                }
              ]
            }
          ]
        },{
          "package_id": "1",
          "modules": [
            {
              "module_id": "1",
              "data": [
                {
                  "data_id": "2"
                }
              ]
            }
          ]
        }
      ]
    }

I've already tried loops inside loops, with constructing multiple arrays and objects. Which causes duplicates or overriding objects into single ones. Is there a more generic way to generate this with JavaScript? (It's for an Angular (6) project.