Search code examples
dataweavemulesoftmule4

Merge corresponding elements from multiple arrays


I have below inputs

input 1:

[{
    "id": "3857"
}, {
    "id": "57"
}]

input 2:

[{
    "Date": "2022-11-30",
    "name": "salesorder",
    "brand": "Apple",
    "Requests": "111",
    "price": "917.65"
}, {
    "Date": "2022-11-13",
    "name": "orders",
    "brand": "TV",
    "Requests": "11",
    "price": "91.60"
}]

input 3:

[{
    "count": "3"
}, {
    "count": "4"
}]

input 4:

[{
    "stock": "21",
    "sold": "112"
}, {
    "stock": "2",
    "sold": "12"
}]

Desired Output:

[{
        "id": "3857",
        "Date": "2022-11-30",
        "name": "salesorder",
        "brand": "Apple",
        "Requests": "111",
        "price": "917.65",
        "count": "3",
        "stock": "21",
        "sold": "112"
    },
    {
        "id": "57",
        "Date": "2022-11-13",
        "name": "orders",
        "brand": "TV",
        "Requests": "11",
        "price": "91.60",
        "count": "4",
        "stock": "2",
        "sold": "12"
    }
]

Solution

  • Assuming that all arrays have the same size you can map each element of the concatenation of the key-values from each item using the index number of each element being mapped ($$ by default).

    %dw 2.0
    output application/json
    var input1=[{"id": "3857"},{"id": "57"}]
    var input2=[{"Date": "2022-11-30","name": "salesorder","brand": "Apple","Requests": "111","price":"917.65"},{"Date": "2022-11-13","name": "orders","brand": "TV","Requests": "11","price": "91.60"}] 
    var input3=[{"count": "3" },{"count": "4" }]
    var input4=[{"stock": "21","sold": "112"},{"stock": "2","sold": "12"}]
    ---
    input1 map (input1[$$] ++ input2[$$] ++ input3[$$] ++ input4[$$])
    

    Output:

    [
      {
        "id": "3857",
        "Date": "2022-11-30",
        "name": "salesorder",
        "brand": "Apple",
        "Requests": "111",
        "price": "917.65",
        "count": "3",
        "stock": "21",
        "sold": "112"
      },
      {
        "id": "57",
        "Date": "2022-11-13",
        "name": "orders",
        "brand": "TV",
        "Requests": "11",
        "price": "91.60",
        "count": "4",
        "stock": "2",
        "sold": "12"
      }
    ]