json - How to accumulate values within a ForEach loop in Mule?

Json - How to accumulate values within a ForEach loop in Mule?

In MuleSoft, you can accumulate values within a forEach loop using the DataWeave language or by using Mule's flow variables. Here's how you can achieve this:

Using DataWeave

DataWeave, MuleSoft's powerful expression language, is often used for data transformation. Here's an example of accumulating values using DataWeave within a Mule application.

Example Scenario

Let's say you have a JSON array of objects, and you want to accumulate a particular field (e.g., amount) from each object.

[ { "id": 1, "amount": 10 }, { "id": 2, "amount": 20 }, { "id": 3, "amount": 30 } ] 

You want to accumulate the amount values to get a total sum of 60.

Mule Flow Configuration

  1. Read the JSON Data: Use the Set Payload component to set the input JSON data (for demonstration purposes).

    <set-payload value='#[[ { "id": 1, "amount": 10 }, { "id": 2, "amount": 20 }, { "id": 3, "amount": 30 } ]]' doc:name="Set Payload"/> 
  2. DataWeave Transform to Accumulate Values: Use a Transform Message component with DataWeave to accumulate the amount values.

    <transform doc:name="Transform Message"> <dw:input-payload mimeType="application/json"/> <dw:set-payload><![CDATA[%dw 2.0 output application/json --- payload reduce ((item, accumulator = 0) -> accumulator + item.amount)]]></dw:set-payload> </transform> 

Full Flow Example

Here's how the full Mule flow would look:

<?xml version="1.0" encoding="UTF-8"?> <mule xmlns:dw="http://www.mulesoft.org/schema/mule/ee/dw" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd"> <flow name="accumulateValuesFlow"> <set-payload value='#[[ { "id": 1, "amount": 10 }, { "id": 2, "amount": 20 }, { "id": 3, "amount": 30 } ]]' doc:name="Set Payload"/> <transform doc:name="Transform Message"> <dw:input-payload mimeType="application/json"/> <dw:set-payload><![CDATA[%dw 2.0 output application/json --- payload reduce ((item, accumulator = 0) -> accumulator + item.amount)]]></dw:set-payload> </transform> </flow> </mule> 

Explanation

  • Set Payload: This component sets the initial JSON array as the payload for demonstration purposes.
  • Transform Message: The DataWeave script processes the JSON array. The reduce function iterates over the array and accumulates the amount values.

Using Flow Variables

If you need to accumulate values using a forEach loop explicitly, you can use flow variables. Here's how you can do it:

  1. Initialize the Variable: Use the Set Variable component to initialize the accumulator variable.

    <set-variable variableName="totalAmount" value="0" doc:name="Set Variable"/> 
  2. For Each Component: Use the For Each component to iterate over the JSON array.

    <foreach collection="#[payload]" doc:name="For Each"> <set-variable variableName="totalAmount" value="#[vars.totalAmount + current.amount]" doc:name="Set Variable"/> </foreach> 
  3. Log the Result: Finally, log the accumulated result.

    <logger message="Total Amount: #[vars.totalAmount]" level="INFO" doc:name="Logger"/> 

Full Flow Example with For Each

<?xml version="1.0" encoding="UTF-8"?> <mule xmlns:dw="http://www.mulesoft.org/schema/mule/ee/dw" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd"> <flow name="accumulateValuesFlow"> <set-payload value='#[[ { "id": 1, "amount": 10 }, { "id": 2, "amount": 20 }, { "id": 3, "amount": 30 } ]]' doc:name="Set Payload"/> <set-variable variableName="totalAmount" value="0" doc:name="Set Variable"/> <foreach collection="#[payload]" doc:name="For Each"> <set-variable variableName="totalAmount" value="#[vars.totalAmount + current.amount]" doc:name="Set Variable"/> </foreach> <logger message="Total Amount: #[vars.totalAmount]" level="INFO" doc:name="Logger"/> </flow> </mule> 

Explanation

  • Set Variable: Initializes the totalAmount variable to 0.
  • For Each: Iterates over the JSON array and updates the totalAmount variable with each amount value.
  • Logger: Logs the accumulated totalAmount.

By using these methods, you can accumulate values within a forEach loop in MuleSoft, either through DataWeave transformations or explicitly using flow variables within a loop.

Examples

  1. "Mule 4 accumulate values in ForEach loop"

    Description: This query seeks guidance on how to accumulate values while iterating through a collection using a ForEach loop in Mule 4. It's a common scenario in Mule projects where data transformation or aggregation is required.

    Code:

    <foreach collection="#[payload]" doc:name="For Each"> <set-variable variableName="accumulator" value="#[vars.accumulator default 0 + payload]" doc:name="Set Accumulator"/> </foreach> 
  2. "Mule iterate and sum values in ForEach"

    Description: This query indicates a need to iterate through a collection in Mule using a ForEach loop and summing up the values encountered during the iteration. It's often used for calculating totals or aggregating data.

    Code:

    <set-variable variableName="total" value="0" doc:name="Set Total"/> <foreach collection="#[payload]" doc:name="For Each"> <set-variable variableName="total" value="#[vars.total + payload]" doc:name="Add to Total"/> </foreach> 
  3. "Mule accumulate values in ForEach loop example"

    Description: This query indicates a search for a practical example demonstrating how to accumulate values within a ForEach loop in Mule. Examples are helpful for understanding the implementation in real-world scenarios.

    Code:

    <set-variable variableName="accumulator" value="[]" doc:name="Initialize Accumulator"/> <foreach collection="#[payload]" doc:name="For Each"> <set-variable variableName="accumulator" value="#[vars.accumulator ++ payload]" doc:name="Add to Accumulator"/> </foreach> 
  4. "Mule ForEach loop add values to list"

    Description: This query suggests a desire to append values to a list while iterating through a collection using a ForEach loop in Mule. It's often used when building or updating lists dynamically during data processing.

    Code:

    <set-variable variableName="list" value="[]" doc:name="Initialize List"/> <foreach collection="#[payload]" doc:name="For Each"> <set-variable variableName="list" value="#[vars.list ++ payload]" doc:name="Add to List"/> </foreach> 
  5. "Mule ForEach loop accumulate JSON values"

    Description: This query specifically targets accumulating JSON values while iterating through a collection using a ForEach loop in Mule. It's relevant when dealing with JSON payloads and needing to aggregate data from them.

    Code:

    <set-variable variableName="accumulator" value="{}" doc:name="Initialize Accumulator"/> <foreach collection="#[payload]" doc:name="For Each"> <set-variable variableName="accumulator" value="#[vars.accumulator ++ payload]" doc:name="Add to Accumulator"/> </foreach> 
  6. "Mule 4 ForEach loop accumulate and store values"

    Description: This query indicates a requirement to accumulate values during a ForEach loop iteration and store them for further processing or output in Mule 4. It's a fundamental operation in Mule flow development.

    Code:

    <set-variable variableName="accumulator" value="0" doc:name="Initialize Accumulator"/> <foreach collection="#[payload]" doc:name="For Each"> <set-variable variableName="accumulator" value="#[vars.accumulator + payload]" doc:name="Add to Accumulator"/> </foreach> 
  7. "Mule iterate over JSON and sum values"

    Description: This query suggests a need to iterate over a JSON payload in Mule and calculate the sum of specific values within the payload. It's a common data manipulation task in Mule integrations.

    Code:

    <set-variable variableName="total" value="0" doc:name="Initialize Total"/> <foreach collection="#[payload]" doc:name="For Each"> <set-variable variableName="total" value="#[vars.total + payload.value]" doc:name="Add to Total"/> </foreach> 
  8. "Mule ForEach loop aggregate data"

    Description: This query indicates a desire to aggregate data from a collection using a ForEach loop in Mule. Aggregating data involves combining multiple values into a single result, which is a common requirement in data processing.

    Code:

    <set-variable variableName="aggregate" value="{}" doc:name="Initialize Aggregate"/> <foreach collection="#[payload]" doc:name="For Each"> <set-variable variableName="aggregate" value="#[vars.aggregate ++ payload]" doc:name="Add to Aggregate"/> </foreach> 
  9. "Mule accumulate values in ForEach loop with condition"

    Description: This query suggests the need to accumulate values within a ForEach loop in Mule but with a condition applied to control which values are included in the accumulation. This adds complexity to the aggregation process.

    Code:

    <set-variable variableName="accumulator" value="0" doc:name="Initialize Accumulator"/> <foreach collection="#[payload]" doc:name="For Each"> <choice doc:name="Include in Accumulation"> <when expression="#[payload &lt; 10]"> <set-variable variableName="accumulator" value="#[vars.accumulator + payload]" doc:name="Add to Accumulator"/> </when> </choice> </foreach> 
  10. "Mule ForEach loop accumulate and transform values"

    Description: This query indicates a need to not only accumulate values but also transform them during a ForEach loop iteration in Mule. Transformation might involve applying functions or mapping values to a different structure.

    Code:

    <set-variable variableName="transformedData" value="[]" doc:name="Initialize Transformed Data"/> <foreach collection="#[payload]" doc:name="For Each"> <set-variable variableName="transformedValue" value="#[payload * 2]" doc:name="Transform Value"/> <set-variable variableName="transformedData" value="#[vars.transformedData ++ transformedValue]" doc:name="Add to Transformed Data"/> </foreach> 

More Tags

mu-law t-sql xcode7 assets angularjs qos operators database-deadlocks django-class-based-views fbsdk

More Programming Questions

More Retirement Calculators

More Fitness-Health Calculators

More Chemical thermodynamics Calculators

More Biology Calculators