I’m facing towards a misbehavior of the function keysOf combined with the method contains.
Given an object like:
{
"keyA":1,
"keyB":2
}
And given the Dataweave script like:
keysOf(payload) contains "keyA"
I’m expecting to have true as outcome, but it returns false.
The keysOf function returns an array containing the keys of the previously mentioned object, like so:
[
"keyA",
"keyB"
]
Which, if used in the following script, it returns the true expected outcome:
[ "keyA", "keyB" ] contains "keyA"
The workaround I tried to implement, storing the keysOf outcome into a variable, doesn’t work either:
%dw 2.0
output application/json
var keysOfPayload=keysOf(payload)
---
keysOfPayload contains "keyA"
The goal of this question, is not to find a workaround, for instance using the question mark selector against the key, works as expected:
%dw 2.0
output application/json
var object= {"keyA":1,"KeyB":2}
---
object.keyA?
Rather, I’m willing to understand why the combination of keysOf and contains is not effective as expected.
>Solution :
The keysOf() works exactly as expected. The problems is a common misconception of how it works. It returns an array of the keys with the Key type. When you try to compare it to a String the comparison returns false correctly.
To make this work you need to do one of two things:
- Recommended use the functions namesOf() instead:
namesOf(a) contains "keyA". Note thatnamesOf()converts the keys to strings and returns an array of Strings. - Convert the
Stringto aKeyexplicitly before using:keysOf(a) contains ("keyA" as Key)