首页 > 解决方案 > 比较两个数组,检查匹配值

问题描述

使用 HubL(当我在 HubSpot 中构建模块时),我有两个数组:

  1. topics: 这是一个主题列表。
  2. all_tags:这是系统中所有博客标签的数组。

如果我转储这些数组,它将返回:

所以本质上,{{ topics }}有一个系统中尚不存在的标签(“洞察力”)。

我要做的是创建第三个数组,它将包含来自上述两个数组的匹配结果。例如topics_final,一旦返回,应该打印[Data, Accounting]

但是,在打印时{{ topics_final }},数组是空的。

我试过的:

<!-- this gets all tags -->
{% set all_tags = blog_topics( blog_id , 250) %}

<!-- create arrays -->
{% set topics = [] %}
{% set topics_final = [] %}

<!-- append topic data to the array -->
{% for item in module.add_topics.topics %}
  {% set topic_option = item|striptags %}
  {% do topics.append( topic_option ) %}
{% endfor %}

<!-- check if topic tags exists in HubSpot -->
{% for topics in all_tags %}
  {% if topics in all_tags %}
    {{ topics }}
    <!-- results with above 
    Data, Accounting, Insight
    -->  
  {% else %}
    else
  {% endif %}
{% endfor %}

有了上面,它只是打印出{{ topics }}, 即使Insight不在all_tags数组中。

注意:标记Jinja2为语法相似

标签: arraysjinja2hubspothubl

解决方案


过滤器reject和内置测试的组合in可以帮助您实现这一目标。

可悲的是,reject过滤器似乎不接受否定测试,但您仍然可以拒绝所有topics不在其中的元素,然后从列表中all_tags拒绝所述元素。topics

所以以:

{{ topics | reject('in', topics | reject('in', all_tags) | list) | list }}

开关产量:

[
    "Data",
    "Accounting"
]

推荐阅读