Translate

Thursday 21 March 2024

Swap key-value pairs in MuleSoft184

 Swap key-value pairs in MuleSoft


Here's a DataWeave expression you can use in MuleSoft 4 to swap key-value pairs in an object within your message payload:



%dw 2.0
output application/json

var payload = {
  "name": "John Doe",
  "age": 30,
  "city": "New York"
};

var swapped = map (payload) $ -> { ($): payload[$$] };

---

swapped // Output: {"John Doe": "name", 30: "age", "New York": "city"}

Explanation:

  1. Define Payload: The payload variable holds a sample object with key-value pairs.

  2. map Function: We use the map function to iterate over each key-value pair in the payload object.

  • $ -> { ($): payload[$$] }: This is the lambda expression defining the logic for each iteration.

  • $: This refers to the current key within the iteration.

  • payload[$$]: This expression accesses the value corresponding to the current key ($) within the payload object. Essentially, it swaps the key and value positions.

  1. Output: The map function creates a new object (swapped) where the keys become the original values and the values become the original keys.

Additional Considerations:

  • Overwriting Keys: If your original object might have duplicate values, the map function will overwrite keys with the same value. The last encountered key-value pair with a duplicate value will be used in the swapped object.

  • Alternative with zip Function (MuleSoft 4.3+): In MuleSoft 4.3 and above, you can utilize the zip function for a more concise approach:



%dw 4.3.0
output application/json

var payload = {
  "name": "John Doe",
  "age": 30,
  "city": "New York"
};

var swapped = zip payload keys payload values;

---

swapped // Output: {"John Doe": "name", 30: "age", "New York": "city"}

The zip function takes two or more arrays and combines them into an array of objects. In this case, it creates an array of objects with keys from payload keys and values from payload values, effectively swapping them.

Choosing the Approach:

The choice between these methods depends on your MuleSoft version and preference. Both achieve the same result. The map function approach might be more readable for earlier versions, while the zip function offers a more compact syntax for MuleSoft 4.3 and above.

By using these techniques, you can effectively swap key-value pairs in objects within your MuleSoft 4 message payloads using DataWeave.


No comments:

Post a Comment

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