I have a dataweave script in which I'm using keysOf
function to return the keys of the JSON payload from inputPayload
as an array of strings in keysList
. I want to compare the returned string with another array of strings keySearch
and see the common strings in both arrays as a new array. Here I'm using reduce
to apply reduction to find the common strings.
%dw 2.0
var inputPayload = {
"name": "John",
"age": 30,
"hobbies": "reading",
"skills": {
"programming": "Java"
}
}
var keysList = keysOf(inputPayload)
var keySearch = ["activities", "age"]
var matchingWords = keysList reduce (item, acc = []) -> if (keySearch contains item) acc + item else acc
output application/json
---
{
keySearch: keySearch,
keysList: keysList,
difference: matchingWords
}
Here the difference
field should print [ "age" ]
but currently it is returning an empty string. If I pass the keysList manually, difference
field will return an array as expected.
eg: var keysList = [ "name", "age", "married", "hobbies", "skills" ]
The keysList
variable has the same array of strings returned from the keysOf
function. Could anyone help in finding why I'm not able to get the difference when using reduce function
Your script has some issues. Probably the main problem is that keysOf()
returns an array of Key
s rather than strings. That could make comparisons to String fail unless you convert the type. Instead it is simpler to use namesOf()
which returns an array of strings.
The second point is not really a an issue, but using reduce() in this manner is not very intuitive and I would say not very suited to to a functional language like DataWeave. It is more logical to me to think that you want to remove the elements that are not in both lists. That is a filtering operation. You can just use filter()
on the array for that. Note that while I said 'remove' DataWeave will always return a new array with the elements removed.
%dw 2.0
var inputPayload = {
"name": "John",
"age": 30,
"hobbies": "reading",
"skills": {
"programming": "Java"
}
}
var keysList = namesOf(inputPayload)
var keySearch = ["activities", "age"]
output application/json
---
{
keySearch: keySearch,
keysList: keysList,
keysMatching: keysList filter (keySearch contains $)
}
Output:
{
"keySearch": [
"activities",
"age"
],
"keysList": [
"name",
"age",
"hobbies",
"skills"
],
"keysMatching": [
"age"
]
}