How do I selectively update fields in an array of objects in dataweave?

Viewed 42

I have the following input arrays :

Array 1:

[
  {
    "count": 3,
    "classification": "Group",
    "id": "",
    "name": "A3200003"
  },
  {
    "count": 1,
    "classification": "Group",
    "id": "",
    "name": "A4000006"
  },
  {
    "count": 1,
    "classification": "Group",
    "id": "",
    "name": "A5E02528190"
  }
]

Array 2:

[
  {
    "count": "1",
    "classification": "Hardware",
    "id": "34265711",
    "name": "A4000006"
  },
  {
    "count": "1",
    "classification": "Hardware",
    "id": "127029226",
    "name": "A5E02528190"
  }
 
]

Now, I only want to update Array 1 where the count = 1 with the values of the Array 2, preserving the order of Array 1 which makes the final output as :

[
  {
    "count": 3,
    "classification": "Group",
    "id": "",
    "name": "A3200003"
  },
  {
    "count": 1,
    "classification": "Hardware",
    "id": "34265711",
    "name": "A4000006"
  },
  {
    "count": 1,
    "classification": "Hardware",
    "id": "127029226",
    "name": "A5E02528190"
  }
]

The keys in the objects of array 1 should be updated with the corresponding values of array 2, only in the objects where the count value = 1, otherwise it should be left unchanged, thus preserving the order of the initial array.

1 Answers

Try with leftJoin as below:

%dw 2.0
output application/json
import * from dw::core::Arrays

var a1 = [
  {
    "count": 3,
    "classification": "Group",
    "id": "",
    "name": "A3200003"
  },
  {
    "count": 1,
    "classification": "Group",
    "id": "",
    "name": "A4000006"
  },
  {
    "count": 1,
    "classification": "Group",
    "id": "",
    "name": "A5E02528190"
  }
]

var a2 = [
  {
    "count": "1",
    "classification": "Hardware",
    "id": "34265711",
    "name": "A4000006"
  },
  {
    "count": "1",
    "classification": "Hardware",
    "id": "127029226",
    "name": "A5E02528190"
  }
 
]
---
    leftJoin(a1, a2, (x) -> x.name, (y) -> y.name) map ($.l - "id" ++ if ($.l.count == 1)
  (
    id: $.r.id
  )
else
  (
    id: $.l.id
  ))
Related