Jekyll液体检查数组是否包含具有特定值的对象

huangapple go评论49阅读模式
英文:

Jekyll Liquid Check if array contains object with specific values

问题

我已经有一个看起来像这样的数组:
[0, 1, 2, 3, {'key': 'test', 'id': 0}]

现在我将一个键分配给变量 key,将一个 id 分配给变量 id,我想检查数组是否包含具有这个键和 id 的对象。

我尝试了以下方式:
{% if arr contains {'key': key, 'id': id} %}
但这总是返回 false。

我该如何正确检查这个?

英文:

I have an array that looks like this:
[0, 1, 2, 3, {'key': 'test', 'id': 0}]

Now I'm assigning a key to a variable key and an id to the variable id and I'd like to check if the array contains an object with said key and id.

I tried the following:
{% if arr contains {'key': key, 'id': id} %}
but this always turns out false.

How could I check for this properly?

答案1

得分: 0

你可以使用where过滤器来检查结果数组的大小。

where过滤器接受两个参数:

  • 用于筛选的属性。
  • 要匹配的值。

你可以将多个where过滤器链接在一起,以根据多个属性进行筛选,例如:

{% assign filteredArray = arr | where: 'key', key | where: 'id', id %}
{% if filteredArray.size > 0 %}
   <!-- 数组包含具有键和ID的对象或没有(大小为0) -->
{% endif %}

Jekyll关于过滤器的文档页面并没有提供更多信息。

英文:

You can check for the size of the resulting array using the where filter.

The where filter takes two arguments:

  • the property to filter on.
  • the value to match.

You can chain multiple where filters together to filter on multiple properties, for example:

{% assign filteredArray = arr | where: &#39;key&#39;, key | where: &#39;id&#39;, id %}
{% if filteredArray.size &gt; 0 %}
   &lt;!-- The array contains an object with key and id or not (size 0) --&gt;
{% endif %}

The Jekyll documentation page about filters is not really telling you more though.

huangapple
  • 本文由 发表于 2023年3月21日 00:04:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75792636.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定