有人可以告诉我使用angularjs中的 groupBy 对数组中的数组进行分组。
假设我有这样的JSON数据:
{
"status": "success",
"country_list": [{
"_id": {
"_id": "100",
"country": "UAE",
}
},
{
"_id": {
"_id": "101",
"country": "India",
}
}
],
"city_list": [{
"_id": {
"_id": "11",
"country_id": "101",
"city": "Chennai",
}
},
{
"_id": {
"_id": "10",
"country_id": "100",
"city": "Dubai",
}
},
{
"_id": {
"_id": "11",
"country_id": "101",
"city": "Mumbai",
}
}
],
"port_list": [{
"_id": {
"_id": "20",
"city_id": "11",
"ports": "Chennai Port"
}
},
{
"_id": {
"_id": "21",
"city_id": "10",
"ports": "Dubai Port"
}
},
{
"_id": {
"_id": "22",
"city_id": "11",
"ports": "MumbaiPort"
}
}
]
}
我应该得到以下结果:
我尝试过使用GroupBy()
但是以一些随机订单结束。任何帮助,将不胜感激。感谢。
答案 0 :(得分:0)
一种方法是使用符合ng-repeat
条件的嵌套ng-if
,以便按_id
s显示相关项目
但请注意,在提供的JSON数据中,您有两个城市Chennai和Mumbai具有相同的_id
,这可能会给您带来意想不到的结果
代码:
angular
.module('App', [])
.controller('DefaultController', function () {
var vm = this;
vm.data = {"status": "success","country_list": [{"_id": {"_id": "100","country": "UAE",}}, {"_id": {"_id": "101","country": "India",}}],"city_list": [{"_id": {"_id": "9","country_id": "101","city": "Chennai",}}, {"_id": {"_id": "10","country_id": "100","city": "Dubai",}}, {"_id": {"_id": "11","country_id": "101","city": "Mumbai",}}],"port_list": [{"_id": {"_id": "20","city_id": "9","ports": "Chennai Port"}}, {"_id": {"_id": "21","city_id": "10","ports": "Dubai Port"}}, {"_id": {"_id": "22","city_id": "11","ports": "Mumbai Port"}}]};
});
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.10/angular.min.js"></script>
<div ng-app="App">
<div class="container" ng-controller="DefaultController as vm">
<ul ng-repeat="country in vm.data.country_list | orderBy: '-_id._id'">
<li>
{{ country._id.country }}
<ul ng-repeat="city in vm.data.city_list">
<li ng-if="country._id._id == city._id.country_id">
{{ city._id.city }}
<ul ng-repeat="port in vm.data.port_list">
<li ng-if="city._id._id == port._id.city_id">
{{ port._id.ports }}
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>