Search code examples
jsonata

JSONata expression to merge two object arrays


I'm trying use JSONata to merge together two object arrays using a filter expression but my expression isn't working. Here is my JSON:

{
  "list1": [
    {"id": "1"},
    {"id": "2"},
    {"id": "3"}
  ],
  "list2": [
    {"key": "1", "value": 1},
    {"key": "2", "value": 2},
    {"key": "3", "value": 3}
  ]
}

and here is my JSONata expression: -

$.list1.({
    "id": id,
    "value": %.list2[key=id].value
})

and I'm expecting

{
  [
    {"id": "1", "value": 1},
    {"id": "2", "value": 2},
    {"id": "3", "value": 3}
  ]
}

The filter isn't working and I think it's because the key is a string type but I can't see a way to wrap my lookup in quotes as it then evaluates id as a string literal. Can anyone help me please?


Solution

  • You have to assign the value of id to a variable in order to use it inside the filter expression, as within that expression the implicit context for your path expressions is already different and local to the array you're filtering (it tries to get id within the list2).

    Here's the working solution:

    $.list1.(
      $id := id;
      {
        "id": $id,
        "value": %.list2[key=$id].value
      }
    )
    

    And you can check it on the live Stedi playground: https://stedi.link/c2N0ypD