在多维数组中按类别列出项目 - jquery
Posted
技术标签:
【中文标题】在多维数组中按类别列出项目 - jquery【英文标题】:Listing items by category in a multidimensional array - jquery 【发布时间】:2016-05-07 17:21:36 【问题描述】:我正在尝试按类别列出我的项目,所以我想展示的是这样的。
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】:这样就可以了:
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);
);
<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>
【讨论】:
这很棒。感谢您的回答。以上是关于在多维数组中按类别列出项目 - jquery的主要内容,如果未能解决你的问题,请参考以下文章