Grouping Json array with Jolt

I have hard time to understand how to group JSON array using Jolt.

I have input like this:

{
  "staff": "David",
  "staffId": "D12345",
  "office": "office A",
  "teachClasses":[
    {
      "className": "Intro to Json",
      "classRoom": "room A",
      "day": "Sunday"
    },
    {
      "className": "Intro to Jolt",
      "classRoom": "room C",
      "day": "Saturday"
    },
    {
      "className": "Intro to Json",
      "classRoom": "room B",
      "day": "Friday"
    },
    {
      "className": "Intro to Javascript",
      "classRoom": "room D",
      "day": "Sunday"
    },
    {
      "className": "Intro to Jolt",
      "classRoom": "room E",
      "day": "Wednesday"
    }
  ]
}

I would like to group by "teachClasses.className" into individual objects in an Array.

Expected output :

[
  {
    "staff": "David",
    "staffId": "D12345",
    "office": "office A",
    "className": "Intro to Json",
    "teachClasses": [
      {
        "className": "Intro to Json",
        "classRoom": "room A",
        "day": "Sunday"
      },
      {
        "className": "Intro to Json",
        "classRoom": "room B",
        "day": "Friday"
      }
    ]
  },
  {
    "staff": "David",
    "staffId": "D12345",
    "office": "office A",
    "className": "Intro to Jolt",
    "teachClasses": [
      {
        "className": "Intro to Jolt",
        "classRoom": "room C",
        "day": "Saturday"
      },
      {
        "className": "Intro to Jolt",
        "classRoom": "room E",
        "day": "Wednesday"
      }
    ]
  },
  {
    "staff": "David",
    "staffId": "D12345",
    "office": "office A",
    "className": "Intro to Javascript",
    "teachClasses": [
      {
        "className": "Intro to Javascript",
        "classRoom": "room D",
        "day": "Sunday"
      }
    ]
  }
]

Is there way to do this? Can you show a sample spec and put some explanation? Also, I am looking for any tutorial to learn the Jolt. Any suggestions?


Solution 1:

You can use @(0,className) as the common value in order to reform objects under common keys, and then trim the key names within the second spec, and pick the leftmost elements by using cardinality spec such as

[
  {
    "operation": "shift",
    "spec": {
      "teachClasses": {
        "*": {
          "@(2,staff)": "@(0,className).staff",
          "@(2,staffId)": "@(0,className).staffId",
          "@(2,office)": "@(0,className).office",
          "@": "@(0,className).&2[]"
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": ""
    }
  },
  {
    "operation": "cardinality",
    "spec": {
      "*": {
        "staff": "ONE",
        "staffId": "ONE",
        "office": "ONE"
      }
    }
  }
]

enter image description here