繁体   English   中英

如何使用过滤器从ng-repeat将数组中的对象分组?

[英]How group objects in array in array from ng-repeat with filter?

如何使用过滤器从ng-repeat中将数组中的对象分组?

我有一个包含对象的数组,我想按对象所在的国家/地区对这些对象进行分组。

样本:我想要这个结果:

Free : Australia, India, United States  
Pay : Australia
Not Pay : Australia, India

来自:

{
"id": 1,
"offer": [
    {
        "id": 9806,
        "country": {
            "name": "Australia"
        },
        "code_show": [
            {
                "code": "Free"
            },
            {
                "code": "Pay"
            },
            {
                "code": "Not Pay"
            }
        ]
    },
    {
        "id": 9807,
        "country": {
            "name": "India"
        },
        "code_show": [
            {
                "code": "Free"
            },
            {
                "code": "Not Pay"
            }
        ]
    },
    {
        "id": 9808,
        "country": {
            "name": "United States"
        },
        "code_show": [
            {
                "code": "Free"
            }
        ]
    }
],
},
{
"id": 2,
"offer": [
    {
        "id": 9806,
        "country": {
            "name": "Australia"
        },
        "code_show": [
            {
                "code": "Free"
            },
            {
                "code": "Not Pay"
            }
        ]
    },
    {
        "id": 9807,
        "country": {
            "name": "Mexico"
        },
        "code_show": [
            {
                "code": "Free"
            }
        ]
    },
    {
        "id": 9808,
        "country": {
            "name": "United States"
        },
        "code_show": [
            {
                "code": "Free"
            }
        ]
    }
]
}

我尝试使用代码:

<ul ng-repeat="(key, value) in offer.code_show | groupBy: 'code_show.code'">
  {{ key }}
  <li ng-repeat="country in value">
    : {{ country.name }} 
  </li>
</ul>

这可能在控制器中更好-主要是因为您将拥有不同的数据结构:

$scope.groupedByCode = {};
$scope.offer.forEach(function(obj) {
    obj["code_show"].forEach(function(code) {
        if (!$scope.groupedByCode[code]) {
            $scope.groupedByCode[code] = [];
        }

        $scope.groupedByCode[code].push(obj);
    });
});

现在,您将每个offer对象包含在具有代码名称的键中,然后进行查看:

<ul ng-repeat="(key, value) in groupedByCode">
    {{ key }}
    <li ng-repeat="country in value">
        : {{ country.country.name }} 
    </li>
</ul>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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