在AngularJS中对对象数组进行分组 [英] Group an array of objects in AngularJS
问题描述
基于如下所示的数组:
var members = [
{name: "john", team: 1},
{name: "kevin", team: 1},
{name: "rob", team: 2},
{name: "matt", team: 2},
{name: "clint", team: 3},
{name: "will", team: 3}
];
我需要为每个团队创建一个无序列表.
I need to create an unordered list for each team.
可以直接使用ngRepeat和过滤器吗?
Can it be done directly with ngRepeat and a filter maybe?
还是更容易将阵列重组为具有成员列表的团队阵列?
Or is it easier to reorganize the array into an array of teams with a list of members?
var teams = [
{id: 1, members: ["john", "kevin"]},
{id: 2, members: ["rob", "matt"]},
{id: 3, members: ["clint", "will"]}
]
嵌套的ngRepeat易于实现,但是我如何以一种简单/巧妙的方式从第一个数组转到该数组呢?
The nested ngRepeat would be easy to implement, but how do I go from the first array to this one in a simple / clever manner?
注意:数组不是来自数据库,而是来自html表.因此,这只是一个简单的成员列表.
function MyController() {
this.members = [
{name: "john", team: 1},
{name: "kevin", team: 1},
{name: "rob", team: 2},
{name: "matt", team: 2},
{name: "clint", team: 3},
{name: "will", team: 3}
];
}
angular.module('app', []);
angular.module('app')
.controller('MyController', MyController);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MyController as ctrl">
<ul>
<li ng-repeat="member in ctrl.members">{{ member.name }} - {{ member.team }}</li>
</ul>
</div>
</div>
推荐答案
您必须group
个项目.为此,我使用了reduce
方法来创建
如下所示的hash
集合:
You have to group
items. For this, I used reduce
method in order to create
a hash
collection which looks like this:
{
"1": [
"john",
"kevin"
],
"2": [
"rob",
"matt"
],
"3": [
"clint",
"will"
]
}
reduce()方法对一个累加器应用一个函数,每个累加器 数组中的元素(从左到右)以将其简化为单个 值.
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
接下来的步骤是在array
中将这个集合map
.为此,您应该使用map
方法.
The following step is to map
this collection in an array
. For this, you should use map
method.
map()方法使用调用a的结果创建一个新数组 在此数组中的每个元素上提供了功能.
The map() method creates a new array with the results of calling a provided function on every element in this array.
var members = [
{name: "john", team: 1},
{name: "kevin", team: 1},
{name: "rob", team: 2},
{name: "matt", team: 2},
{name: "clint", team: 3},
{name: "will", team: 3}
];
var groups = members.reduce(function(obj,item){
obj[item.team] = obj[item.team] || [];
obj[item.team].push(item.name);
return obj;
}, {});
var myArray = Object.keys(groups).map(function(key){
return {team: key, name: groups[key]};
});
console.log(myArray);
这篇关于在AngularJS中对对象数组进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!