Translate

Tuesday 20 February 2024

Assign incremental keys to the objects in an array In MuleSoft 05

 Assign incremental keys to the objects in an array In MuleSoft


Sure, here is how youcan assign incremental keys to the objects in an array in MuleSoft 4:


XML

<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:ee="http://www.mulesoft.org/extensions/ee"
      xmlns:db="http://www.mulesoft.org/extensions/db"
      xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ee/4.4.0 http://www.mulesoft.org/schema/mule/ee/4.4.0/mule.xsd">

    <flow name="assign_keys_flow">

        <set-payload value="#[payload.map { it << ['key': 1] }.toList()]" />

        <logger message="Modified data: #[payload]" level="INFO" />

    </flow>

</mule>

This Mule flow uses a set-payload component to achieve this. The set-payload component takes the input JSON array and applies a map expression to it. The map expression iterates over each object in the array and adds a new key-value pair "key": 1 to it. The toList() method converts the resulting list of objects back into an array.

The modified data is then logged to the console using a logger component.

You can modify this flow to suit your specific needs, such as using a different starting value for the key or adding additional logic to the map expression.

Here is an example of how the flow would work with the sample data you provided:


JSON

[
  {
    "name": "Alice",
    "age": 30,
    "key": 1
  },
  {
    "name": "Bob",
    "age": 25,
    "key": 1
  },
  {
    "name": "Charlie",
    "age": 35,
    "key": 1
  }
]

As you can see, each object in the array now has a new key-value pair "key": 1.


No comments:

Post a Comment

Note: only a member of this blog may post a comment.