Search code examples
jsonata

Grouping array of objects by property value with JSONata


I want to transform this array of objects:

{
  "Phone": [
    {
      "type": "home",
      "number": "0203 544 1234"
    },
    {
      "type": "office",
      "number": "01962 001234"
    },
    {
      "type": "office",
      "number": "01962 001235"
    },
    {
      "type": "mobile",
      "number": "077 7700 1234"
    }
  ]
}

into an array of objects, which groups phone numbers by type:

[
    {
        "type": "home",
        "numbers": ["0203 544 1234"]
    },
    {
        "type": "office",
        "numbers": ["01962 001234", "01962 001235"]
    },
    {
        "type": "mobile",
        "numbers": ["077 7700 1234"]
    }
]

with JSONata. Any hints?

I've tried this:

Phone{type: number}

But that leads to a different structure:

{
  "home": "0203 544 1234",
  "office": [
    "01962 001234",
    "01962 001235"
  ],
  "mobile": "077 7700 1234"
}

Solution

  • I think you're on the right track, and you just need to apply additional transformation at the end to transform the grouped object into an array:

    {
      "Phone": Phone{
        type: number
      } ~> $each(function($value, $key) {{
        "type": $key,
        "number": $value
      }})
    }
    

    Check it out on the Stedi playground: https://stedi.link/JO7kBed