ModelWorks logoModelWorks
JSON TransformArray

groupBy

Group an array of objects into a keyed object

groupBy

Reduces an array of objects into an object whose keys are the values of key and whose values are arrays of the matching elements.

Options

OptionTypeRequiredDefaultDescription
keystringYesField whose value to group elements by.

Example

Input

JSON
[
  { "role": "user", "content": "Hi" },
  { "role": "assistant", "content": "Hello" },
  { "role": "user", "content": "How are you?" }
]

Operation

JSON
{ "type": "groupBy", "options": { "key": "role" } }

Output

JSON
{
  "user": [
    { "role": "user", "content": "Hi" },
    { "role": "user", "content": "How are you?" }
  ],
  "assistant": [
    { "role": "assistant", "content": "Hello" }
  ]
}

In a Circuit Step

JSON
{
  "name": "messages_by_role",
  "description": "Group conversation turns by role",
  "function": "circuit.core.transform.json",
  "input": {
    "source": "${{ messages }}",
    "operations": [
      { "type": "groupBy", "options": { "key": "role" } }
    ]
  },
  "outputs": [
    {
      "name": "grouped_messages",
      "description": "Messages bucketed by role",
      "value": "${{ messages_by_role.output.transformed_result }}"
    }
  ]
}

Notes & gotchas

  • Errors with groupBy: expected array if the input is not an array.
  • Group keys are produced by reading the field value: strings are used directly as clean keys (no embedded quotes); numbers and objects are stringified via Value::to_string() (e.g. 42, {"a":1}).
  • A missing field on an element groups it under "null".
  • Output is an Object, so the next operation in the pipeline must be one that accepts objects (e.g., pick, entries).
On this page

On this page