1
votes

I get a payload as input in the message transform component. It is an Array with Objcts:

 [
      {
          "enterprise": "Samsung",
          "description": "This is the Samsung enterprise",
      },
      {
          "enterprise": "Apple",
          "description": "This is the Apple enterprise ",
      }
  ]

I have a variable that replaces the description and the output that I want is:

[
      {
          "enterprise": "Samsung",
          "description": "This is the var value",
      },
      {
          "enterprise": "Apple",
          "description": "This is the var value",
      }
  ]

I tried to use:

 %dw 2.0
 output application/java
 ---
 payload map ((item, index) -> {

     description: vars.descriptionValue
 })

But it returns:

 [
      {
          "description": "This is the var value",
      },
      {
          "description": "This is the var value",
      }
  ]

Is possible to replace only the description value keeping the rest of the fields? Avoiding adding the other fields in the mapping.

1

1 Answers

2
votes

There are many ways to do this.

One way to do it is to first remove the original description field and then add the new one

%dw 2.0
output application/java
---
payload map ((item, index) -> 
    item - "description" ++ {description: vars.descriptionValue}
)

Otherwise you can use mapObject to iterate over the key-value pairs of each object and with pattern matching add a case for when the key is description. I prefer this second way of doing it when I want to do many replacements.

%dw 2.0
output application/java
fun process(obj: Object) = obj mapObject ((value, key) -> {
    (key): key match {
        case "description" -> vars.descriptionValue
        else -> value
    }
})
---
payload map ((item, index) -> 
    process(item)
)