如何从另一个数组创建一个数组,其中某些键与 Dataweave 2.0 中的值匹配?

How to create an array from another array where certain keys matches a value in Dataweave 2.0?

我有以下有效负载,我需要从中提取错误[] != null 的行以及 ID 和日期与错误行的 ID 和日期匹配的所有其他行。

[
  {
    "Id": "123",
    "Date": "1/1/2021",
    "line": "ABC",
    "Error": ["Some Error 1", "Some Error 2"]
  },
  {
    "Id": "123",
    "Date": "1/1/2021",
    "line": "CDB",
    "Error": []
  },
  {
    "Id": "123",
    "Date": "2/2/2021",
    "line": "ABC",
    "Error": []
  }
]

从上面的数组中,我需要获取行

  1. 错误[] != null
  2. 获取日期和 ID 与对象匹配且错误为 != null 的所有其他行

此处所需的输出应为:

[
  {
    "Id": "123",
    "Date": "1/1/2021",
    "line": "ABC",
    "Error": ["Some Error 1", "Some Error 2"]
  },
  {
    "Id": "123",
    "Date": "1/1/2021",
    "line": "CDB",
    "Error": []
  }
]

由于 第二个对象的 ID 和日期与错误 != null 的第一个对象匹配,我需要将所有这些放入一个数组中。

如何获得所需的输出负载? 我可以过滤掉 Error != null 的行,但是如何获取 ID 和 Date 与错误行匹配的所有其他行?

你可以试试这个方法。

%dw 2.0
output application/json
---
(payload groupBy ($.Id) mapObject {
  ($ groupBy ($.Date) mapObject {
      ($$):$
  })
})[0]

另一种方法,但我不喜欢在 groupBy 中串联

%dw 2.0
output application/json
---
payload filter ($.Error != null) groupBy ($.Id ++ "_" ++ $.Date)  mapObject {
    ($$):$
}

用两个过滤器完成了这个。首先过滤以查找与错误相关的所有日期数组。找到原始数组中具有相同日期的所有实例并合并到数组中:

%dw 2.0
output application/json
var data = [
  {
    "Id": "123",
    "Date": "1/1/2021",
    "line": "ABC",
    "Error": ["Some Error 1", "Some Error 2"]
  },
  {
    "Id": "123",
    "Date": "1/1/2021",
    "line": "CDB",
    "Error": []
  },
  {
    "Id": "123",
    "Date": "2/2/2021",
    "line": "ABC",
    "Error": []
  }
]
---
/*An array of dates that contain Error information with default [] to
* account for instances where no errors are present
*/
(data filter (not isEmpty($.Error))) default []
// Filter the data again to add find all objects with that Date and add to 
// an array
    reduce ((item, acc=[]) -> acc ++ (data filter (item.Date == $.Date and item.Id == $.Id)))