Search code examples
jsonata

Spread syntax in Jsonata?


I would like to just add a key/value pair to a object and therefore not enlist all of the objects attributes again. Something similar to javascripts ... Spread syntax.

{
    'address': $.customer.addresses[id=$$.shippingAddressId].{
        ...?,
        'fullName': firstName & ' ' & lastName
    }
}

I looked through the documentation and searched the web, but could not find anything regarding this feature.

What were I expecting?

Actually, I would have been surprised if it had been implemented, but since Jsonata is so awesome, it could have been.

EDITED:

You can write the transformation like this (improves readablility):

{
    'address': $.customer.addresses[id=$$.shippingAddressId].{
        'street': street,
        'city': city,
        'fullName': firstName & ' ' & lastName
    }
}

The question stems from pure curiosity

If someone knows a better way, I would be interested, otherwise I will continue to marvel at its beauty.


Solution

  • If I'm understanding the question correctly, given the following data (I had to make some assumptions because no data was provided):

    Data

    {
      "customer": {
        "firstName": "Alex",
        "lastName": "Jäger",
        "addresses": [
          {"id": "home", "street": "123 Main Street", "city": "MyTown"},
          {"id": "work", "street": "987 South Street", "city": "AnyTown", "spreadMeInAlso": "something"},
          {"id": "school", "street": "654 North Street", "city": "YourTown"}
        ]
      },
      "shippingAddressId": "work"
    }
    

    Query

    This query, using the Transform Operator, will allow you to create the fullName and essentially "spread in" the remaining values:

    {
        'address': $.customer.addresses[id=$$.shippingAddressId] ~> | $ | {
            "fullName": $$.customer.firstName & ' ' & $$.customer.lastName
        } |
    }
    

    Output

    {
      "address": {
        "id": "work",
        "street": "987 South Street",
        "city": "AnyTown",
        "spreadMeInAlso": "something",
        "fullName": "Alex Jäger"
      }
    }
    

    Working example: https://try.jsonata.org/Py1y6SOqe