Search code examples
muledataweavemulesoftmule4mule-esb

dataweave - How to join the list of sku with same order in one object in the array


How to join the list of sku with same order in one object in the array.

Input:

[{
 "number": "7358",
 "sku": "301-01",
 "desc": "1"
}, {
 "number": "7358",
 "sku": "301-02",
 "desc": "2"
}, {
 "number": "7359",
 "sku": "301-03",
 "desc": "3"
}, {
 "number": "7359",
 "sku": "301-03",
 "desc": "4"
}, {
 "number": "7360",
 "sku": "301-03",
 "desc": "5"
}]

Output:

[{
  "number": "7358",
  "list": [{
      "sku": "301-01",
      "desc": "1"
  }, {
      "sku": "301-02",
      "desc": "2"
  }]
}, {
  "number": "7359",
  "list": [{
      "sku": "301-03",
      "desc": "3"
  }, {
      "sku": "301-03",
      "desc": "4"
  }]
}, {
  "number": "7360",
  "list": [{
      "sku": "301-03",
      "desc": "5"
  }]
}]

Output we just create a new "list" array that contains the skus and the desc that have the order in common. Any help would be appreciated. Thank you.


Solution

  • Hi The best way as shown by Salim is the groupBy I did a few modifications

    %dw 2.0
    output application/json
    ---
    payload 
        groupBy ((item, index) -> item.number)
        mapObject ((value, key, index) -> 
            {
                number: key,
                list: value map ((item, index) -> item - "number") //We remove the number field
            }
        )
    

    Simple the key of the groupBy is the criteria that was group so it is the number and the simplest way to re build the output structure is by doing the map and removing the "number" field