anxiousAvocado
anxiousAvocado

Reputation: 187

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

I have the below payload from which I need to extract rows where Error[] != null and all other rows where the Id and Date match the errored row's Id and Date.

[
  {
    "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": []
  }
]

From the above array, I need to get rows where

  1. Error[] != null
  2. Get all other rows where the Date and ID matches the object with Error != null

Desired Output here should be :

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

Since the Id and Date of 2nd Object match the first object where Error != null, I need to get all those into one array.

How can I achieve the desired output payload? I am able to filter out rows where Error != null, but how do I get all other rows where the Id and Date match to the errored rows?

Upvotes: 0

Views: 1232

Answers (2)

maddestroyer7
maddestroyer7

Reputation: 263

Accomplished this with two filters. First filter to find all an array of dates that pertain to errors. find all instances in the original array that have the same date and combine into array:

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

Upvotes: 3

Salim Khan
Salim Khan

Reputation: 4303

You could try with this approach.

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

Another approach but i don't like concatenating in groupBy

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

enter image description here

Upvotes: 1

Related Questions