maomifadacai
maomifadacai

Reputation: 369

how to transform array object to nested array object on dataweave

I am using Mule 4.4 and Dataweave 2.x from csv file to get following records example,

[
    {
    "sold": "B001",
    "org": "SS",
    "soNo": "so001',
    "sku": "A001",
    "qty": 2
},
{
    "sold": "B001",
    "org": "SS",
    "soNo": "so001',
    "sku": "A002",
    "qty": 3
},
{
    "sold": "B002",
    "org": "SS",
    "soNo": "so002',
    "sku": "A001",
    "qty": 4
}
]

Each element in array represents a row of data and each row has hierarchical data (Header and detailItem), the output what I expected are below, "sold" and "soNo" are unique key ,

[{
    "sold": "B001",    
    "soNo": "so001',
    "org": "SS",
    "items": 
    [{
     "sku": "A001",
     "qty": 2
     },
     {
    "sku": "A002",
    "qty": 3
     }
     },
     {
     "sold": "B002",
    "soNo": "so002',
     "org": "SS",
    "items": 
    [{
     "sku": "A001",
     "qty": 4
     }]
     }  ]

Upvotes: 0

Views: 85

Answers (1)

StackOverflowed
StackOverflowed

Reputation: 759

use groupBy to group the required keys and map to transform to desired output format:

%dw 2.0
output application/json  
---
payload groupBy ($.sold ++ $.soNo ++ $.org) pluck {
  ($[0] - "sku" - "qty"),
  items: ($ map ($ - "sold" - "soNo" - "org"))
}

Upvotes: 1

Related Questions