0
votes

I have a list of maps (listOfMapsObject) like below

[
 {
  "Id" : "1234",
  "Value" : "Text1"
  },
  {
  "Id" : "1235",
  "Value" : "Text2"
  }
]

I would like access "Value" field for a given Id in dataweave script. For example: For Id = 1234, Text1 should be returned.

%dw 1.0
%output application/json
%var listOfMapsObject = flowVars.listOfMaps
---
payload map {
    "key" : $.key,
    "data" : lookup Value field in listOfMapsObject by given key 
}
2

2 Answers

2
votes

Approch suggested by @'sulthony h' is fine but it will end up in performance issue if you large number of data in pyload and listOfMapsObject. As filter is used , for each record of payload script will loop for all the entries in flowVars.listOfMaps.

Following will work fine and map key value only once.

%dw 1.0
%output application/json 
%var dataLookup = {(flowVars.listOfMaps map {
        ($.Id): $.Value
     })}
---
payload map {
    key : $.key,
    data : dataLookup[$.key]
}

Output-

[
  {
    "key": "1234",
    "data": "Text1"
  },
  {
    "key": "1235",
    "data": "Text2"
  }
]

Where Payload -

[
 {
  "key" : "1234" 
  },
  {
  "key" : "1235"
  }
]

And -

[
 {
  "Id" : "1234",
  "Value" : "Text1"
  },
  {
  "Id" : "1235",
  "Value" : "Text2"
  }
]

Hope this helps.

0
votes

I create my own object with the slightly similar object and successfully access "value" field with the following DataWeave expression:

%dw 1.0
%output application/json
%var listOfMapsObject = flowVars.listOfMaps
---
payload map using(data = $) {
    "key" : data.key,
    "data" : (listOfMapsObject filter $.id == data.key).value reduce ($$ ++ $)
}

You can modify it with your own object, e.g.: replace the "id" with "Id". Test and evaluate the result by using filter, flatten, reduce, etc.