javascript - 在 AngularJS 中对一组对象进行分组

标签 javascript angularjs arrays function

基于一个看起来像这样的数组:

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}
];

我需要为每个团队创建一个无序列表。

可以直接用 ngRepeat 和过滤器来完成吗?

还是将数组重新组织成具有成员列表的团队数组更容易?
var teams = [
  {id: 1, members: ["john", "kevin"]},
  {id: 2, members: ["rob", "matt"]},
  {id: 3, members: ["clint", "will"]}
]

嵌套的 ngRepeat 很容易实现,但是如何以简单/巧妙的方式从第一个数组转到这个数组?

注意:数组不是来自数据库,而是来自 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看起来像这样的集合:

{
  "1": [
    "john",
    "kevin"
  ],
  "2": [
    "rob",
    "matt"
  ],
   "3": [
     "clint",
      "will"
   ]
}

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.



下一步是到map这个集合在 array .为此,您应该使用 map方法。

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);

关于javascript - 在 AngularJS 中对一组对象进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43247333/

相关文章:

javascript - 在 mousemove 上播放视频时出现抽搐

javascript - 来自 soap 的动态 justgage 值

javascript - 如何将焦点设置到溢出 :scroll 的 div

angularjs - onFinishRender 没有被触发

c - 将指针的值分配给二维数组

php - 如何在单击时更改文本字段的值?

json - AngularJS POST json 到 SilverStripe API

angularjs - 在生产环境中选择 Angularjs 的依赖项

javascript - Google Scripts - SMS 短信脚本的延迟循环

javascript - 比较javascript中的多维数组