0
votes

Given the input, dataweave and output, I wonder why do I see reference of "banana" in "apple" array elements. For example, in the attached screenshot, I have highlighted a portion and I was expecting to see "apple-1" instead of "banana-apple-1". I am going to attach the input, dataweave and the output in text format in this post.

Input:

{
    "apple":{
        "options":[
            {
                "id": "1",
                "name": "apple-one"
            },
            {
                "id": "2",
                "name": "apple-two"
            },
            {
                "id": "3",
                "name": "apple-three"
            }
        ]
    },
    "banana":{
        "options":[
            {
                "id": "4",
                "name": "banana-four"
            },
            {
                "id": "5",
                "name": "banana-five"
            },
            {
                "id": "6",
                "name": "banana-six"
            }
        ]
    },
    "orange":{
        "options":[
            {
                "id": "7",
                "name": "orange-seven"
            },
            {
                "id": "8",
                "name": "orange-eight"
            },
            {
                "id": "9",
                "name": "orange-nine"
            }
        ]
    }
}

Dataweave:

%dw 2.0
output application/json
---
payload.apple.options map ($ mapObject ((value, key, index) -> {
    ((key) : "apple-" ++ value) if ((key) as String == "id"),
    ((key) : value ) if ((key) as String != "id")
        }
    )
)

++


payload.banana.options map ($ mapObject ((value, key, index) -> {
    ((key) : "banana-" ++ value) if ((key) as String == "id"),
    ((key) : value ) if ((key) as String != "id")
        }
    )
)

Output:

[
  {
    "id": "banana-apple-1",
    "name": "apple-one"
  },
  {
    "id": "banana-apple-2",
    "name": "apple-two"
  },
  {
    "id": "banana-apple-3",
    "name": "apple-three"
  },
  {
    "id": "banana-4",
    "name": "banana-four"
  },
  {
    "id": "banana-5",
    "name": "banana-five"
  },
  {
    "id": "banana-6",
    "name": "banana-six"
  }
]

DataWeave Playground snippet

1

1 Answers

0
votes

Try with this ( you are missing the ( ) around each of map output that you build)

%dw 2.0
output application/json
---
(payload.apple.options map ($ mapObject ( {
    (($$) : "apple-" ++ $) if (($$) as String == "id"),
    (($$) : $ ) if (($$) as String != "id")
        }
    
)))

++


(payload.banana.options map ($ mapObject ( {
    (($$) : "banana-" ++ $) if (($$) as String == "id"),
    (($$) : $ ) if (($$) as String != "id")
        }
    )
))