Search code examples
dataweavemulesoft

Dataweave Mulesoft from array to object with reduce?


In Mulesoft dataweave I have to change an array in an object. I tried it with reduce but for some reason it does not work. Dataweave 2.0 and Anypoint platfrom version 4.4.0

{
    "option1": 0,
    "option2": 100,
    "options": [
        {
            "itemnr": "111111",
            "color": "red",
            "parts": 12,
            "year": 2022
        },
        {
            "itemnr": "222222",
            "color": "blue",
            "parts": 14,
            "year": 2022
        }
    ]
}

This must be the outcome:

{
    "Abs": {
        "El": {
            "Fields": {
                "itemnr": "111111",
                "date": "2022-08-02",
                "parts": 12,
                "color": "red"
            },
            "Fields": {
                "itemnr": "222222",
                "date": "2022-08-02",
                "parts": 14,
                "color": "blue"
            }
        }
    }
}

I tried this but really strange things happening, code is displayed in reverse order.

{Abs :
    {El :
        {fields :
            (payload.options) map  {
                itemnr: $.itemnr,
                date: now() as Date,
                parts: $.parts,
                color: $.color
            } reduce ((item, accumulator) -> (item ++ {fields: accumulator}))
        }
    }
}

What am I doing wrong ?


Solution

  • Its the code (item ++ {fields: accumulator}) . Changing it like below will give you your desired result.

    {Abs :
        {El :
             
                (payload.options map  {
                    itemnr: $.itemnr,
                    date: now() as Date,
                    parts: $.parts,
                    color: $.color
                }) reduce ((item, accumulator = {}) -> accumulator ++ {Fields:item})
            
        }
    }