gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:18:56 26 4
gpt4 key购买 nike

如何使用过滤器从 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>

最佳答案

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

$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 对象都放在一个带有代码名称的键中,然后只需创建 View :

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

关于javascript - 如何使用过滤器从 ng-repeat 中将数组中的对象分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35042740/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com