Lookup list of Maps variable in data weave script

社会主义新天地 提交于 2019-12-25 09:15:31

问题


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 
}

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/39301428/lookup-list-of-maps-variable-in-data-weave-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!