0

I have the following input data

[
  {
    "key": "a",
    "value": [
      "1"
    ]
  },
  {
    "key": "a",
    "value": [
      "2"
    ]
  },
  {
    "key": "b",
    "value": [
      "3"
    ]
  }
]

and would like to merge the values into an array, grouped by the same key. i.e. the following desired output:

[
  {
    "key": "a",
    "value": [
      "1",
      "2"
    ]
  },
  {
    "key": "b",
    "value": [
      "3"
    ]
  }
]

any help is appreciated thank you!

2 Answers 2

3

One option can be using groupBy and then accommodating the groups you get like this:

valuesOf(payload groupBy ((item, index) -> item.key)) 
    map ((group, index) -> {
    "key": group[0].key,
    "value": flatten(group.value)
})

This is producing the output you shared.

Sign up to request clarification or add additional context in comments.

Comments

2

Similar approach. a bit different usage of functions.

%dw 2.0
output application/json
---
payload groupBy ($."key") mapObject {
    "key": $[0].key,
    "value": $ map {
        temp: $.value[0]
    }.temp
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.