且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用树枝订购一个对象数组

更新时间:2022-11-28 17:10:38

{% set data = [{国家":法国",'匹配':'G',},{'国家' : '比利时','匹配':'F',},{国家":法国",'匹配':'E',},{'国家' : '德国','匹配':'D',},{'国家' : '德国','匹配':'C',},{国家":法国",'匹配':'B',},{国家":意大利",'匹配':'A',},] %}{% 设置排序 = [] %}{% for row in data %}{% if not ((row.country) in sorted|keys) %}{% set sorted = sorted|merge({ (row.country) : [], }) %}{% endif %}{% set sorted = sorted|merge({(row.country): (sorted[(row.country)]|merge([ row.match, ])|sort)}) %}{% endfor %}{% 代表国家,值排序 %}{{ 国家 }}{% 代表价值 %}- {{ 价值 }}{% endfor %}----------------------------{% endfor %}

演示

I need to order a list of objects i receive with an inner property.

I receive a list of objects like that :
{ match: "italy - germany", date: "27/01/2019", competion: "World cup" }
{ match: "lille - paris", date: "23/01/2019", competion: "coupe de france" }
{ match: "om - psg", date: "13/01/2019", competion: "coupe de france" }
{ match: "russia - poland", date: "25/01/2019", competion: "World cup" }

I don't know where to start but i need to loop over matches: {% for match in matches %}

I want to obtain this list:

coupe de france :

  • om - psg
  • lille -paris

world cup :

  • italy germany
  • russia - poland

{% set data = [
    {
        'country' : 'france',
        'match': 'G',
    },
    {
        'country' : 'belgium',
        'match': 'F',
    },
    {
        'country' : 'france',
        'match': 'E',
    },
        {
        'country' : 'germany',
        'match': 'D',
    },
    {
        'country' : 'germany',
        'match': 'C',
    },
        {
        'country' : 'france',
        'match': 'B',
    },
    {
        'country' : 'italy',
        'match': 'A',
    },  
] %}


{% set sorted = [] %}
{% for row in data %}
    {% if not ((row.country) in sorted|keys) %}{% set sorted = sorted|merge({ (row.country) : [], }) %}{% endif %}
    {% set sorted = sorted|merge({(row.country): (sorted[(row.country)]|merge([ row.match, ])|sort)}) %}
{% endfor %}

{% for country, values in sorted %}
    {{ country }}
    {% for value in values %}
        - {{ value }}
    {% endfor %}
----------------------------
{% endfor %}

demo