0

I have a problem with counting the number of occurences of a string from an array in a field in an object.

The XML below has 3 'Level3' items with 1 'TextLine' field each.

I need to count how many times each text in the variable 'texts' occurs in the payload.

fun getVasCount(texts) = 
    sizeOf (Level1.*Level2.*Level3.*TextLine filter (texts contains $))

So instead of getting the count:2 I got the count:3 because 'a text' is a substring of 'This is a text'

var texts = {
    "This is a text": "",
    "This is another text": ""
}

<?xml version="1.0" encoding="UTF-8"?>
<ns:Level1
    xmlns:ns="aaaa:bbbb:cccc:dddd">
    <Level2>
        <Level3>
            <TextLine>This is a text</TextLine>
        </Level3>
        <Level3>
            <TextLine>This is a text</TextLine>
        </Level3>
        <Level3>
            <TextLine>a text</TextLine>
        </Level3>
    </Level2>
</ns:Level1>
1
  • Why instead of contains you don't use == ? Commented Jun 18, 2019 at 13:51

1 Answer 1

2

A way to do it is to count occurrences for each different texts grouping them by value and counting how many elements are in each group. And then modify your texts object with the counts.

%dw 2.0
output application/json
var texts = {
    "This is a text": "",
    "This is another text": ""
}
var textLines = payload.Level1.*Level2.*Level3.*TextLine default []
var grouped = textLines 
    groupBy $ 
    mapObject (groupValues, text) -> {(text): sizeOf(groupValues)}
---
texts mapObject {($$): grouped[$$] default 0}

The result would be:

{
  "This is a text": 2,
  "This is another text": 0
}

Note: Not really modifying texts, since objects are immutable, it's creating a new one.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.