简体   繁体   中英

access the index of the item inside reduce function in dataweave 2.0

My DataWeave code looks like below:-

Result: Data reduce (item,ls={}) -> ls ++ From: {dev: item.warehouse}

Is there way to check the index of item object. I need to do conditional based on the index of the item object.

Example: Item = Data[0] do this;

Result: Data reduce (item,ls={}) -> ls ++ From: {dev: item.warehouse}

Item = Data[1] do this;

Result: Data reduce (item,ls={}) -> ls ++ To: {dev: item.warehouse}

Original Code looks like below:

Result : ( Data  reduce (
             item,ls={}) -> ls ++ 
From:{id: "111",(if (item.sign == "333") {status: "OPEN"} else if (item.sign == "444") {status: "HOLD"} else {status: item.sign})}

I need to add "From" whenever the index of Item is odd number and add "To" whenever the index of item is even.

Since I don't have the conditional, I am always getting "From"

No you can't access any indexes, here's the documentation of reduce https://docs.mulesoft.com/mule-runtime/4.1/dw-core-functions-reduce

What you can do is count the items yourself by modifying the structure of your accummulator: ls={counter=0,data={}}

Now you can use the counter to add one per iteration and keep track of things: {counter: ls.counter + 1, data: ls.data ++ To: {dev: item.warehouse}}

As you can understand you would need to add a conditional to differentiate between the From and To .

If I have time later on I 'll do it for you, or somebody else can beat me to it.

EDIT: here's the best I can do based upon your question, but you should get the idea:

%dw 2.0
output application/dw
var inputdata = [{warehouse: 100},{warehouse: 56}, {warehouse:1000}]
---
inputdata reduce (
    (e, acc={c: 0, data: {From: {}, To: {}}}) ->
        {
            c: acc.c+1,
            data: {
                From: if (isEven(acc.c)) (acc.data.From ++ {warehouse: e.warehouse}) else acc.data.From,
                To: if (isEven(acc.c)) acc.data.To else (acc.data.To ++ {warehouse: e.warehouse})
            }
        } 
)

Always provide appropriate sample inputs and outputs of your transformation if you want to get the most out of the DW SO community;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM