How do I check if a key exists in any of the dictionaries inside an array?

Viewed 26

Is it possible to check if any of the dictionaries contains a specific key, preferably without looping through them? I got an array (cart.items) returned that looks like this:

[
  {
    "line_level_discount_allocations": [],
    "line_level_total_discount": 0,
    "selling_plan_allocation": {
      "price_adjustments": [
        {
          "position": 1,
          "price": 9500
        }
      ],
      "price": 9500,
      "compare_at_price": 9500,
      "per_delivery_price": 9500,
      "selling_plan": {
        "id": "xxxxx",
        "name": "Ships every 1 month",
        "description": null,
        "options": [
          {
            "name": "1 Month(s), 2 Month(s), 3 Month(s)",
            "position": 1,
            "value": "1 Month(s)"
          }
        ],
        "recurring_deliveries": true,
        "price_adjustments": [
          {
            "order_count": null,
            "position": 1,
            "value_type": "percentage",
            "value": 0
          }
        ]
      },
      "checkout_charge_amount": 9500,
      "remaining_balance_charge_amount": 0
    }
  },
  { 
    "line_level_discount_allocations": [],
    "line_level_total_discount": 0
  }
]

I need to check if any of the cart.items has a selling_plan_allocation.

Would it be possible to do something like (pseudo code below)

  • If any dictionary contains "selling_plan_allocation" -> do something

  • If no dictionary in the array contains "selling_plan_allocation" -> do something else.

I would prefer to avoid having to loop over the list and checking each individual index. Is there some nifty shortcut?

E.g

{% if cart.items contains selling_plan_allocation %}
  array has at least one dictionary with `selling_plan_allocation`
{% else %}
  no dictionary has any `selling_plan_allocation`
{% endif %}

Perhaps there is a way better way, but the reason I'd like to check for any selling_plan_allocation is because I got a table like this:

<!-- if no `selling_plan_allocation` is found at all, don't render the table -->
<table>
  <thead>
  </thead>
  <tbody>
    {%- for item in cart.items -%}
      {% if item.selling_plan_allocation != nil %}
        <!-- my data here, <tr> and <td> etc -->
      {% endif %}
    {% endfor %}
  </tbody>
</table>

If no selling_plan_allocation is found, I don't want to render the table above at all, but if I put the for loop outside the <table> part, it would make a new table for each cart item, when in reality I just want to loop through and only make one body - not one table

0 Answers
Related