Search code examples
jsonjsonata

Merge Json Array Nodes and roll up a child element


I have a requirement to roll a collection of nodes that uses the current node name (within the collection) and for the value take each child nodes value (single node) into a string array, then use the parents key as the key.

Given.

{
  "client": {
    "addresses": [
      {
        "id": "27ef465ef60d2705",
        "type": "RegisteredOfficeAddress"
      },
      {
        "id": "b7affb035be3f984",
        "type": "PlaceOfBusiness"
      },
      {
        "id": "a8a3bef166141206",
        "type": "EmailAddress"
      }
    ],
    "links": [
      {
        "id": "29a9de859e70799e",
        "type": "Director",
        "name": "Bob the Builder"
      },
      {
        "id": "22493ad4c4fd8ac5",
        "type": "Secretary",
        "name": "Jennifer"
      }
    ],
    "Names": [
      {
        "id": "53977967eadfffcd",
        "type": "EntityName",
        "name": "Banjo"
      }
    ]
  }
}

from this the output needs to be

{
  "client": {
    "addresses": [
      "RegisteredOfficeAddress",
      "PlaceOfBusiness",
      "EmailAddress"
    ],
    "links": [
      "Director",
      "Secretary"
    ],
    "Names": [
      "EntityName"
    ]
  }
}

What is the best way to achieve this? Any pointers to what/how to do this would be greatly appreciated.

Ron.


Solution

  • You can iterate over entries of your client object first with the help of the $each function, then get types for each of them, and combine via $merge:

    {
      "client": client 
        ~> $each(function($list, $key) {{ $key: $list.type }}) 
        ~> $merge
    }
    

    Live playground: https://stedi.link/OpuRdE9