Reputation: 25
I have an array with a single index that has a JSON object that contains three different string arrays, which I have to map into a single one based on each index. for example all first index from each array into one single JSON object and so on...
Is it possible in Dataweave Transformation?
Input
[{
"id": [
"123",
"456",
"789"
],
"name": [
"Test Brand 1",
"Test Brand 2",
"Test Brand 3"
],
"address": [
"Via Roma 1",
"Via Milano 1",
"Via Napoli 1"
]
}]
Desired output:
[
{
"Key1": "123",
"Key2": "Test Brand 1",
"Key3": "Via Roma 1"
},
{
"Key1": "456",
"Key2": "Test Brand 2",
"Key3": "Via Milano 1"
},
{
"Key1": "789",
"Key2": "Test Brand 3",
"Key3": "Via Napoli 1"
}
]
Upvotes: 1
Views: 2131
Reputation: 263
I took a swing at this just to make it dynamic so it would work for any amount of keys that were in the arrays. It gets a little confusing since you don't have access to the index in reduce. Enjoy!
%dw 2.0
output application/json
import indexOf from dw::core::Arrays
var data = [{
"id": [
"123",
"456",
"789"
],
"name": [
"Test Brand 1",
"Test Brand 2",
"Test Brand 3"
],
"address": [
"Via Roma 1",
"Via Milano 1",
"Via Napoli 1"
]
}]
---
(data flatMap valuesOf($)) map ((valuesArray) -> valuesArray reduce ((value, acc={}) -> acc ++ {
("key$(indexOf(valuesArray,value) + 1)"): value
}))
output:
[
{
"key1": "123",
"key2": "456",
"key3": "789"
},
{
"key1": "Test Brand 1",
"key2": "Test Brand 2",
"key3": "Test Brand 3"
},
{
"key1": "Via Roma 1",
"key2": "Via Milano 1",
"key3": "Via Napoli 1"
}
]
Upvotes: 0
Reputation: 935
You can try the below code where we don't need to do iteration (looping) two times and no need to flatten.
%dw 2.0
output application/json
var id = payload[0].id
---
id map (item2, index2) -> {
"Key1": item2,
"Key2": payload[0].name[index2],
"Key3": payload[0].address[index2]
}
it will give the same result.
[
{
"Key1": "123",
"Key2": "Test Brand 1",
"Key3": "Via Roma 1"
},
{
"Key1": "456",
"Key2": "Test Brand 2",
"Key3": "Via Milano 1"
},
{
"Key1": "789",
"Key2": "Test Brand 3",
"Key3": "Via Napoli 1"
}
]
Thanks
Upvotes: 0
Reputation: 1296
You can try the following DataWeave expression, assuming that each array will always contain the same number of items:
%dw 2.0
output application/json
---
flatten(payload map (item, index1) ->
item.id map (item2, index2) -> {
"Key1": item2,
"Key2": item.name[index2],
"Key3": item.address[index2]
})
Output (address names were changed to make sure the transformation works as expected):
[
{
"Key1": "123",
"Key2": "Test Brand 1",
"Key3": "Via Roma 1"
},
{
"Key1": "456",
"Key2": "Test Brand 2",
"Key3": "Via Milano 2"
},
{
"Key1": "789",
"Key2": "Test Brand 3",
"Key3": "Via Napoli 3"
}
]
Upvotes: 2