How to use nested "map"

1.6k views Asked by At

I would like to map a json, based on some nested attribute, but somehow there seems to be a stupid mistake I make.

My input:

[
  {
    "productNo": "00011111",
    "items": [
      {
        "color": "000000000006000060",
      },
      {
        "color": "000000000006000061",
      }
    ]
  },      
  {
    "productNo": "00022222",
    "items": [
      {
        "color": "000000000006000060"
      },
      {
        "color": "000000000006000061"
      }
    ]
  }
]

My transformation:

%dw 2.2
output application/json

---
payload map ( prod , indexOfProd ) -> { 
        (prod.items map (prodItem, indexOfProdItem) -> {
            PNR: prod.productNo,
            Color: color.quantity       
        })
            
}

My result:

[
  {
    "PNR": 00011111,
    "Color": "000000000006000060",
    "PNR": 00011111,
    "Color": "000000000006000061"
  },
  {
    "PNR": 00022222,
    "Color": "000000000006000060",
    "PNR": 00022222,
    "Color": "000000000006000061"
  }
]

My expected result / What I'm trying to get:

[
  {
    "PNR": 00011111,
    "Color": "000000000006000060"
  },
  {
    "PNR": 00011111,
    "Color": "000000000006000061"
  },
  {
    "PNR": 00022222,
    "Color": "000000000006000060"
  },
  {
    "PNR": 00022222,
    "Color": "000000000006000061"
  }
]

Any hint why it's not separating the results based on the color variations?

2

There are 2 answers

0
olamiral On BEST ANSWER

You can use the following dataweave expression:

%dw 2.0
output application/json
---
flatten(payload map (item, index) -> item.items map (subItem, subIndex) -> {
    "PNR": item.productNo,
    "Color": subItem.color
})

0
Salim Khan On

Another variation using your existing solution Martin.

%dw 2.0
output application/json

---
flatten (payload map ( prod , indexOfProd ) -> { 
        temp: (prod.items map (prodItem, indexOfProdItem) -> {
            PNR: prod.productNo,
            Color: prodItem.color     
        })
            
}.temp)