Understanding array.ForEach() Function with an Example
The example in this section illustrates an array, cakes.
Consider the example below which is available for you to experiment with at https://github.com/TIBCOSoftware/tci-flogo/tree/master/samples/app-dev/array.forEach.sample.
{ "cakes":[ { "id":"0001", "type":"donut", "name":"Bundt Cake", "ppu":0.55, "batters":{ "batter":[ { "id":"1001", "type":"Regular" }, { "id":"1002", "type":"Chocolate" }, { "id":"1003", "type":"Blueberry" }, { "id":"1004", "type":"Devil's Food" } ] }, "topping":[ { "id":"5001", "type":"None" }, { "id":"5002", "type":"Glazed" }, { "id":"5005", "type":"Sugar" }, { "id":"5007", "type":"Powdered Sugar" }, { "id":"5006", "type":"Chocolate with Sprinkles" }, { "id":"5003", "type":"Chocolate" }, { "id":"5004", "type":"Maple" } ] }, { "id":"0002", "type":"Butter Cake", "name":"Raised", "ppu":0.55, "batters":{ "batter":[ { "id":"1001", "type":"Regular" } ] }, "topping":[ { "id":"5001", "type":"None" }, { "id":"5002", "type":"Glazed" }, { "id":"5005", "type":"Sugar" }, { "id":"5003", "type":"Chocolate" }, { "id":"5004", "type":"Maple" } ] }, { "id":"0003", "type":"Biscuit Cake", "name":"Old Fashioned", "ppu":0.55, "batters":{ "batter":[ { "id":"1001", "type":"Regular" }, { "id":"1002", "type":"Chocolate" } ] }, "topping":[ { "id":"5001", "type":"None" }, { "id":"5002", "type":"Glazed" }, { "id":"5003", "type":"Chocolate" }, { "id":"5004", "type":"Maple" } ] } ] }
In the above example, the cakes array has two nested arrays called topping and batter. You can use array.forEach() function to iterate the cakes array or you can also iterate its nested arrays, topping or batter while iterating the cakes array. Basically, you can iterate through nested arrays while iterating through the parent array.
array.forEach($flow.body.cakes,"cakes",$loop.type=="donut")
- $ flow.body.cakes is the source array to iterate over.
- "cakes" is the scopeName. This is the scope for your mapping. Each scope has a name to it. By default, the scope name is the same as the name of the source array, in this case "cakes".
-
$loop.type=="donut" is the condition to filter the array elements.
The above example displays as follows in the mapper:
array.forEach($flow.body.cakes,"cakes",$loop.type=="donut")
array.forEach($loop[cakes].batters.batter,"batter",$loop.type=="Regular")
Here, $loop[cakes] indicates that the cakes parent array is being iterated over and during each iteration of the cakes array, the batter array is also being iterated.
array.forEach($loop[cakes].topping,"topping",$loop.type=="Powdered Sugar")
Here, while iterating the cakes parent array, we are also iterating over the topping array.