I have a payload of an array of objects. Within each object contains a key that has values that are also arrays of objects. I am trying to combine all of the keys that match, and condense down to an array of the values at the smallest level.
Here is an example payload-
[
{
"randomNumbers": [
{
"aFewDigits": "124374"
}
]
},
{
"randomNumbers": [
{
"aFewDigits": "103865"
},
{
"aFewDigits": "103868"
},
{
"aFewDigits": "103739"
},
{
"aFewDigits": "103866"
}
]
},
{
"randomNumbers": [
{
"aFewDigits": "103864"
},
{
"aFewDigits": "103737"
},
{
"aFewDigits": "103862"
},
{
"aFewDigits": "103860"
}
]
}
]
I’ve tried using this dataweave map script to pull out the values from each array-
%dw 2.0
output application/json
---
payload map{
aFewDigits: $..aFewDigits
}
However, this is the result I am getting-
[
{
"aFewDigits": [
"124374"
]
},
{
"aFewDigits": [
"103865",
"103868",
"103739",
"103866"
]
},
{
"aFewDigits": [
"103864",
"103737",
"103862",
"103860"
]
}
]
I would like for my result to look like this-
[
{
"aFewDigits": [
"124374",
"103865",
"103868",
"103739",
"103866",
"103864",
"103737",
"103862",
"103860"
]
}
]
3
Answers
You can achieve the desired output by using the reduce function
The script iterates over each item in the input array using the reduce function. For each item, it concatenates the aFewDigits arrays of all the items into a single array. Finally, it returns an object with the concatenated aFewDigits array.
DataWeave Script
Output:
A solution with just using selectors and
flatten()
:Output:
An alternative solution using
flatMap()
:Just customizing your solution. You dont need to apply map for your solution since descendant keys are same. You can refer Dataweave Selectors for further details
DataWeave
Output