简体   繁体   中英

Count items in array with Liquid

I have a json object like the following:

    "results"=>{
        "data"=>[
            {
                "id"=>"letters",
                "values"=>["A", "B", "B", "X"]
            },
        ]
    }

I am trying to count how many A 's and how many B 's and then add them.

This is my code so far:

require 'liquid'
Liquid::Template.error_mode = :strict
@template = Liquid::Template.parse('
    {% assign letters = results.data | where: "id", "letters" %}
    {{ letters }}
    {% increment a_count %}
    {% increment b_count %}
    {% for letter in letters.values %}
        {% if letter contains "A" %}
            {% increment a_count %}
        {% endif %}
        {% if letter contains "B" %}
            {% increment b_count %}
        {% endif %}
    {% else %}
        The collection is empty.
    {% endfor %}
    {% assign count = a_count | plus: b_count %}
    {{ a_count}} + {{ b_count }} = {{ count }}
')
print(@template.render(
    "results"=> {
        "data"=> [
            {
                "id"=> "letters",
                "values"=> ["A", "B", "B", "X"]
            },
        ]
    }
), { strict_variables: true })
print(@template.errors) 

But this doesn't work and I get this output:



    {"id"=>"letters", "values"=>["A", "B", "B", "X"]}
    0
    0

        The collection is empty.


    1 + 1 = 2

Which is confusing because results.values is not empty and I only call increment once for each a_count and b_count which should set the initial value to 0 .

The output of print(@template.errors) is only:

{:strict_variables=>true}[]

How do I count how many A 's and how many B 's are in the letters.values array?

Is it possible for you to combine it with JS? You can pass the array to a JS function and do there ther rest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM