'Mule dataweave transformation

I have below json as my input payload and I want to fetch groupvalue where groupname is b. How to do this in dataweave ?

[
  {
    "groupName": "a",
    "groupvalue": "1234"
  },
  {
    "groupName": "b",
    "groupvalue": "7890"
  }
]


Solution 1:[1]

If you are absolutely sure there is only one element in the array with groupName equal to "b":

%dw 2.0
output application/json
---
(payload filter ($.groupName == "b") map ( $.groupvalue)) [0]

With your input I get the following output:

"7890"

Solution 2:[2]

In case, there are a number of key, value pairs for groupName "b", this code will give you an array of the groupvalue for groupName "b"s.

%dw 2.0
output application/json
---
(payload filter ((item, index) -> item.groupName == "b"))["groupvalue"]

For example:

    payload = [
  {
    "groupName": "a",
    "groupvalue": "1234"
  },
  {
    "groupName": "b",
    "groupvalue": "7890"
  },
  {
    "groupName": "b",
    "groupvalue": "8330"
  }
]

You will get:

[
  "7890",
  "8330"
]

Solution 3:[3]

In case, there are a number of key, value pairs for groupName "b", this code will give you an array of the groupvalue for groupName "b"s.

%dw 2.0
output application/json
---
(payload filter $.groupName =="b").*groupvalue

example:-

payload = [
  {
    "groupName": "a",
    "groupvalue": "1234"
  },
  {
    "groupName": "b",
    "groupvalue": "7890"
  },
  {
    "groupName": "b",
    "groupvalue": "8330",
    "groupvalue": "1234"
  }
]

example 2

payload = [
  {
    "groupName": "a",
    "groupvalue": "1234"
  },
  {
    "groupName": "b",
    "groupvalue": "7890"
  },
  {
    "groupName": "b",
    "groupvalue": "8330"
  }
]

script:-

%dw 2.0
output application/json
---
(payload filter $.groupName =="b")..groupvalue

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 tleo
Solution 3 Sandeep Sai Kumar