繁体   English   中英

Map 多个字符串 Arrays 使用 Dataweave 成单个数组

[英]Map multiple string Arrays using Dataweave into a single Array

I have an array with a single index that has a JSON object that contains three different string arrays, which I have to map into a single one based on each index. 例如,每个数组中的所有第一个索引到一个单独的 JSON object 等等......

Dataweave 转换是否可行?

输入

[{
    "id": [
          "123",
          "456",
          "789"
        ],
    "name": [
          "Test Brand 1",
          "Test Brand 2",
          "Test Brand 3"
        ],
    "address": [
          "Via Roma 1",
          "Via Milano 1",
          "Via Napoli 1"
        ]
}]

所需的 output:

[
    {
        "Key1": "123",
        "Key2": "Test Brand 1",
        "Key3": "Via Roma 1"
    },
    {
        "Key1": "456",
        "Key2": "Test Brand 2",
        "Key3": "Via Milano 1"
    },
    {
        "Key1": "789",
        "Key2": "Test Brand 3",
        "Key3": "Via Napoli 1"
    }
]

您可以尝试以下 DataWeave 表达式,假设每个数组将始终包含相同数量的项目:

%dw 2.0
output application/json
---
flatten(payload map (item, index1) -> 
    item.id map (item2, index2) -> {
        "Key1": item2,
        "Key2": item.name[index2],
        "Key3": item.address[index2]
    })

Output(地址名称已更改以确保转换按预期工作):

[
  {
    "Key1": "123",
    "Key2": "Test Brand 1",
    "Key3": "Via Roma 1"
  },
  {
    "Key1": "456",
    "Key2": "Test Brand 2",
    "Key3": "Via Milano 2"
  },
  {
    "Key1": "789",
    "Key2": "Test Brand 3",
    "Key3": "Via Napoli 3"
  }
]

您可以尝试下面的代码,我们不需要进行两次迭代(循环)并且不需要展平。

%dw 2.0
output application/json
var id = payload[0].id
---
id map (item2, index2) -> {
        "Key1": item2,
        "Key2": payload[0].name[index2],
        "Key3": payload[0].address[index2]
    }

它会给出相同的结果。

[
  {
    "Key1": "123",
    "Key2": "Test Brand 1",
    "Key3": "Via Roma 1"
  },
  {
    "Key1": "456",
    "Key2": "Test Brand 2",
    "Key3": "Via Milano 1"
  },
  {
    "Key1": "789",
    "Key2": "Test Brand 3",
    "Key3": "Via Napoli 1"
  }
]

谢谢

我在此使用了 swing 只是为了使其动态化,因此它适用于 arrays 中的任意数量的键。 由于您无法访问 reduce 中的索引,因此有点令人困惑。 享受!

%dw 2.0
output application/json
import indexOf from dw::core::Arrays
var data = [{
    "id": [
          "123",
          "456",
          "789"
        ],
    "name": [
          "Test Brand 1",
          "Test Brand 2",
          "Test Brand 3"
        ],
    "address": [
          "Via Roma 1",
          "Via Milano 1",
          "Via Napoli 1"
        ]
}]
--- 
(data flatMap valuesOf($)) map ((valuesArray) -> valuesArray reduce ((value, acc={}) -> acc ++ {
    ("key$(indexOf(valuesArray,value) + 1)"): value
}))

output:

[
  {
    "key1": "123",
    "key2": "456",
    "key3": "789"
  },
  {
    "key1": "Test Brand 1",
    "key2": "Test Brand 2",
    "key3": "Test Brand 3"
  },
  {
    "key1": "Via Roma 1",
    "key2": "Via Milano 1",
    "key3": "Via Napoli 1"
  }
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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