简体   繁体   中英

Dataweave in Mule - Change value Array of Objects

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 .

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)
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM