Rony Singh
Rony Singh

Reputation: 39

Using JOLT to split array based on an attirbute

I am trying to use JOLT to split an array into multiple arrays based on an attribute. I have tried JOLT "Shift" spec but cannot achieve it.

I have looked at couple of links where array transformation is done, but I cannot find any way to split the array into multiple arrays.

Example: Convert following array into 3 arrays based on the value of attribute "type".

Input:

[
  {
    "name": "abc1",
    "address": "abcdef",
    "types": [
      "a",
      "b"
    ]
  },
  {
    "name": "abc2",
    "address": "abcdef2",
    "types": [
      "b",
      "c"
    ]
  },
  {
    "name": "abc3",
    "address": "abcdef3",
    "types": [
      "c"
    ]
  }
]

Output:

{
  "a": [
    {
      "name": "abc1",
      "address": "abcdef",
      "types": [
        "a",
        "b"
      ]
    }
  ],
  "b": [
    {
      "name": "abc1",
      "address": "abcdef",
      "types": [
        "a",
        "b"
      ]
    },
    {
      "name": "abc2",
      "address": "abcde2",
      "types": [
        "b",
        "c"
      ]
    }
  ],
  "c": [
    {
      "name": "abc2",
      "address": "abcde2",
      "types": [
        "b",
        "c"
      ]
    },
    {
      "name": "abc3",
      "address": "abcdef3",
      "types": [
        "c"
      ]
    }
  ]
}

Upvotes: 0

Views: 1573

Answers (1)

Matthew Warman
Matthew Warman

Reputation: 3442

This will produce the desired result:

  1. for each element in types
  2. Use value of array (&1) as key
  3. Go up 3 levels and copy that as value (@3)
[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "types": {
          "*": {
            "*": {
              "@3": "&1"
            }
          }
        }
      }
    }
  }
]

Upvotes: 2

Related Questions