Mule 中的 Dataweave - 更改对象数组的值

Dataweave in Mule - Change value Array of Objects

我在消息转换组件中获得了一个有效负载作为输入。这是一个包含对象的数组:

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

我有一个替换描述的变量,我想要的输出是:

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

我尝试使用:

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

     description: vars.descriptionValue
 })

但是 returns:

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

是否可以仅替换描述值而保留其余字段? 避免在映射中添加其他字段

有很多方法可以做到这一点。

一种方法是先删除原来的描述字段,然后添加新的

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

否则,您可以使用 mapObject 遍历每个对象的键值对,并使用 pattern matching 添加一个 case 用于描述键。 当我想做很多替换时,我更喜欢第二种方法。

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