Search code examples
muledataweavemulesoftmule4mule-esb

Dataweave 2 - How can i join 2 arrays by index inside object without lose data parent object


How to join 3 arrays by index (lines, pckSlip and linesDt) and generate an arrays object by linesDt after that you have to generate a new field "totalCost" which is to add the "cost" field of all cost elements in the linesDt array, note the "number" field in the original object is preserved for all new elements spawned from the parent.

Input:

{
  "lines":[
    {
       "requestedQuantity":1,
       "pendingQuantity":0
    },
    {
       "requestedQuantity":2,
       "pendingQuantity":0
    }
 ],
 "number":"98",
 "pckSlip":[
    {
       "trackingNumber":"10534",
       "boxesNum":1
    },
    {
       "trackingNumber":"00049",
       "boxesNum":1
    }
 ],
 "linesDt":[
    {
       "number":"5678",
       "cost":7.7
    },
    {
     "number":"1234",
     "cost":7.3
    }
 ]
}

Ouput:

[
  {
     "number":"5678",
     "cost":7.7,
     "requestedQuantity":1,
     "pendingQuantity":0,
     "trackingNumber":"10534",
     "boxesNum":1,
     "totalCost":15,
     "order":"98"
  },
  {
     "number":"1234",
     "cost":7.3,
     "requestedQuantity":2,
     "pendingQuantity":0,
     "trackingNumber":"00049",
     "boxesNum":1,
     "totalCost":15,
     "order":"98"   
  }
]

NOTE: We generate 2 new elements because they are the total of indices found in "linesDt" within an array of elements.

Any help would be appreciated. Thank you.


Solution

  • Mapping each element of lines gives you the index to use in the other arrays. The ++ operator can be used to concatenate objects all the objects together. The calculated fields are added just as another object.

    %dw 2.0
    output application/json
    var totalCost = sum(payload.linesDt.*cost)
    ---
    payload.lines map (
        $ 
        ++ payload.pckSlip[$$]
        ++ payload.linesDt[$$]
        ++ {totalCost: totalCost, order: payload.number}
    )
    

    Output:

    [
      {
        "requestedQuantity": 1,
        "pendingQuantity": 0,
        "trackingNumber": "10534",
        "boxesNum": 1,
        "number": "5678",
        "cost": 7.7,
        "totalCost": 15.0,
        "order": "98"
      },
      {
        "requestedQuantity": 2,
        "pendingQuantity": 0,
        "trackingNumber": "00049",
        "boxesNum": 1,
        "number": "1234",
        "cost": 7.3,
        "totalCost": 15.0,
        "order": "98"
      }
    ]