Search code examples
mulemule-studiomule-componentdataweaveanypoint-studio

Add new items to JSON array after dynamic lookup


My sample payload is given below.

{
  "Identifier": "1111111111",
  "Type": "Test",
  "Codes": [
    {
      "CodeId": "112233-ABC",
      "Code": {
        "ID": "112233",
        "Name": "ABC"
      }
    },
    {
      "CodeId": "445566-DEF",
      "Code": {
        "ID": "445566",
        "Name": "DEF"
      }
    },
    {
      "CodeId": "778899-GHI",
      "Code": {
        "ID": "778899",
        "Name": "GHI"
      }
    }
  ]
}

I have 2 session variables as well given below:

%var var1 = 
{
  "112233": "900123",
  "445566": "900456",
  "778899": "900789"
}

%var var2 = 
{
  "value": [
    {
      "Desc": "Alpha",
      "TempId": 900123
    },
    {
      "Desc": "Bravo",
      "TempId": 900456
    },
    {
      "Desc": "Charlie",
      "TempId": 900789
    }
  ]
}

What I need is to do a dynamic lookup against these 2 variables and add new attribute(s) to the main payload, as given below:

{
  "Identifier": "1111111111",
  "Type": "Test",
  "Codes": [
    {
      "CodeId": "112233-ABC",
      "Code": {
        "ID": "112233",
        "Name": "ABC",
        "Description": "Alpha"
      }
    },
    {
      "CodeId": "445566-DEF",
      "Code": {
        "ID": "445566",
        "Name": "DEF",
        "Description": "Bravo"
      }
    },
    {
      "CodeId": "778899-GHI",
      "Code": {
        "ID": "778899",
        "Name": "GHI",
        "Description": "Charlie"
      }
    }
  ]
}

The idea is to perform lookup using value from var1 against TempId in var2 and get Desc. This has to be added to the Code array by matching with ID. If no value found, then insert null. I am on dataweave 1.0

Thanks in advance


Solution

  • You can try the below script. There are two lookups, first is from var to get the TempId and then second is to add Desc field

    %dw 1.0
    %input payload application/json
    %output application/json
    %var var1 = 
    {
      "112233": "900123",
      "445566": "900456",
      "778899": "900789"
    }
    %var var2 = 
    {
      "value": [
        {
          "Desc": "Alpha",
          "TempId": 900123
        },
        {
          "Desc": "Bravo",
          "TempId": 900456
        },
        {
          "Desc": "Charlie",
          "TempId": 900789
        }
      ]
    }
    %var var2Grouped = var2.value groupBy $.TempId
    %function addDesc(id) var2Grouped[var1[id]][0].Desc  default {}
    ---
    {
      Identifier: payload.'Identifier',
      'Type': payload.'Type',
      "Codes": payload."Codes" map ((code) -> {
        CodeId: code.CodeId,
        Code: code.Code ++ addDesc(code.Code.ID)
      })
    }