在多维数组中按类别列出项目 - jquery

时间:2016-01-29 20:36:11

标签: jquery arrays angularjs multidimensional-array foreach

我想按类别列出我的项目,所以我要展示的是这样的。

A类

第1项

第2项

B类

第1项

第3项

第4项

C类

第3项

第4项

这是我拥有的数组,我该如何打印我的类别并列出下面的项目? $scope.categoryArray = [ {name:"Item 1", on: false, subcategory:"Category A"}, {name:"Item 2", on: false, subcategory:"Category A"}, {name:"Item 1", on:false, subcategory:"Category B"}, {name:"Item 3", on: false, subcategory:"Category B"}, {name:"Item 4", on: false, subcategory:"Category B"}, {name:"Item 3", on: false, subcategory:"Category C"}, {name:"Item 4", on: false, subcategory:"Category C"}];

提前感谢您的意见!

1 个答案:

答案 0 :(得分:0)

这样做:



var app = angular.module("app", []);
app.controller("c", function($scope) {
  $scope.categoryArray = [{
    name: "Item 1",
    on: false,
    subcategory: "Category A"
  }, {
    name: "Item 2",
    on: false,
    subcategory: "Category A"
  }, {
    name: "Item 1",
    on: false,
    subcategory: "Category B"
  }, {
    name: "Item 3",
    on: false,
    subcategory: "Category B"
  }, {
    name: "Item 4",
    on: false,
    subcategory: "Category B"
  }, {
    name: "Item 3",
    on: false,
    subcategory: "Category C"
  }, {
    name: "Item 4",
    on: false,
    subcategory: "Category C"
  }];
  $scope.array = [];

  for (var item in $scope.categoryArray) {
    var obj = $scope.array[$scope.categoryArray[item].subcategory];
    if (!obj)
      $scope.array[$scope.categoryArray[item].subcategory] = [];
    $scope.array[$scope.categoryArray[item].subcategory].push($scope.categoryArray[item].name);

  }
  var str = "";
  for (var cat in $scope.array) {
    str += cat + "</br>";
    for (var item in $scope.array[cat]) {
      str += $scope.array[cat][item] + "</br>";
    }
  }
  $("#content").html(str);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="c" id="content"></div>
&#13;
&#13;
&#13;