Matching Array values in mule 4 using dataweave

孤人 提交于 2020-12-14 23:39:22

问题


I am trying to match the specific value from input payload using dataweave.

Input:

{
    "drives": [{
        "id": "0AEzOyzyCb7Uk9PVA",
        "name": "SFJob-2020-10"
    }, {
        "id": "0AMEHi1wsq-8FUk9PVA",
        "name": "SFJobs-2020-11"
    } ],
    "nextPageToken": "~!!~AI9FV7RV4uSXy20zpCBTP2LFWCXS0c"
},
{
    "drives": [{
        "id": "0AEz3mOyzyCb7Uk9PVA",
        "name": "Dev2020-10"
    }, {
        "id": "0AMEHi1wsq-8FUk9PVA",
        "name": "Dev2020-11"
    }],
"nextPageToken": "~!!~AI9P2LFWCXS0c"
}

how can i check whether value "Dev2020-10" is present or not.

i am using below code giving me error.

%dw 2.0
output application/json
---
payload.drives filter ((item, index) -> item.name == 'Dev2020-10')

Expected output:

[ {

"id": "0AEz3mOyzyCb7Uk9PVA",
"name": "Dev2020-10"

} ]

How can i achieve this?


回答1:


First, the input is not valid. I assume that it is supposed to be a JSON array so I enclosed into brackets: [ {..},{..} ].

After that you will notice that the filter is expecting a single object, but because it is an array you need to map it first. To return a single array I used a flatMap():

%dw 2.0
output application/json
---
payload flatMap $.drives filter ((item, index) -> item.name == 'Dev2020-10')

Output:

[
  {
    "id": "0AEz3mOyzyCb7Uk9PVA",
    "name": "Dev2020-10"
  }
]



回答2:


The solution can be thought of two steps:

  1. Merge all the drives together to get a single array of objects flatten(inputArray.drives)
  2. Filter the new array of objects based on the search criteria filter ((item, index) -> item.name == "Dev2020-11")

The solution will be this :

%dw 2.0
output application/json

var inputArray = [
    {
    "drives": [{
        "id": "0AEzOyzyCb7Uk9PVA",
        "name": "SFJob-2020-10"
    }, {
        "id": "0AMEHi1wsq-8FUk9PVA",
        "name": "SFJobs-2020-11"
    } ],
    "nextPageToken": "~!!~AI9FV7RV4uSXy20zpCBTP2LFWCXS0c"
    },
    {
    "drives": [{
        "id": "0AEz3mOyzyCb7Uk9PVA",
        "name": "Dev2020-10"
    }, {
        "id": "0AMEHi1wsq-8FUk9PVA",
        "name": "Dev2020-11"
    }],
"nextPageToken": "~!!~AI9P2LFWCXS0c"
    }
]
---
flatten(inputArray.drives) filter ((item, index) -> item.name == "Dev2020-11") 

To learn more about flatten method, refer the documentation : mule 4 doc



来源:https://stackoverflow.com/questions/64784201/matching-array-values-in-mule-4-using-dataweave

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