William Good
William Good

Reputation: 109

JOLT transformation add element to array

I want to use a jolt transformation to add an element to an array.

My approach is to use default to append to the last element in the array

Input

{
  "options": [
    {
      "name": "Will",
      "state": "enabled"
    },
    {
      "name:": "Bert",
      "state": "enabled"
    },
    {
      "name": "Kate",
      "state": "disabled"
    }
  ]
}

Jolt Spec

[
  {
    "operation": "default",
    "spec": {
      "options[]": {
        "3": {
          "name": "Bob",
          "state": "enabled"
        }
      }
    }
  }
]

Desired Output

{
  "options": [
    {
      "name": "Will",
      "state": "enabled"
    },
    {
      "name": "Bert",
      "state": "enabled"
    },
    {
      "name": "Kate",
      "state": "disabled"
    },
    {
      "name": "Bob",
      "state": "enabled"
    }
  ]
}

It works if the input array length is 3. How can I obtain the array length and set the index dynamically?

Upvotes: 2

Views: 7464

Answers (1)

Milo S
Milo S

Reputation: 4586

A little hokey, but possible.

Spec

[
  {
    // default in the new "thing first"
    "operation": "default",
    "spec": {
      "temp": {
        "name": "Bob",
        "state": "enabled"
      }
    }
  },
  {
    // copy the options array across first, 
    //  then copy the value (map with Bob) to "options"
    //  which is an array, so Shift will add it to the end
    "operation": "shift",
    "spec": {
      "options": "options",
      "temp": "options"
    }
  }
]

Upvotes: 4

Related Questions