簡體   English   中英

如何在 Angular JS 中更改 JSON 數據格式?

[英]how to change JSON data format in angular JS?

我是 Angular JS 的新手。

我的 JSON 數據是:

{
"CheckList": [
   {
    "UnitClass": "Budget Space",
    "CheckListCategoryId": 1,
    "CheckListCategory": "DOORS",
    "CheckListItemId": 2,
    "CheckListItem": "Deadbolt, Locksets, and keys all functioning"
   }, 
   {
    "UnitClass": "Budget Space",
    "CheckListCategoryId": 2,
    "CheckListCategory": "WINDOWS",
    "CheckListItemId": 46,
    "CheckListItem": "Windows are operable"
   }, 
   {
    "UnitClass": "Budget Space",
    "CheckListCategoryId": 2,
    "CheckListCategory": "WINDOWS",
    "CheckListItemId": 13,
    "CheckListItem": "Window pane is not broken or cracked"
   }
}

我想把它改成:

{
"CheckList": [
   {
    "UnitClass": "Budget Space",
    "CheckListCategoryId": 1,
    "CheckListCategory": "DOORS",
    "CheckListItemId": 2,
    "CheckListItem": "Deadbolt, Locksets, and keys all functioning"
   }, 
   {
    "UnitClass": "Budget Space",
    "CheckListCategoryId": 2,
    "CheckListCategory": "WINDOWS",
    "CheckListItems": [
        {
            "CheckListItem": "Windows are operable",
            "CheckListItemId": 46,
        },
        {
            "CheckListItem": "Window pane is not broken or cracked",
            "CheckListItemId": 13,
        }]
   }
}

為什么我這樣做:

我有一個 Bootstrap 折疊列表作為


視窗

我正在使用 ng-repeat,在CheckListCategoryId上添加一個“唯一”過濾器

但問題在於我當前的 JSON,只有一個CheckListItem被發布,但在許多情況下有兩個。 就像在 WINDOWS 中一樣。

如何更改 JSON 數據?

還有一件事。 我目前的方法是正確的還是有其他選擇?

您可以使用angular-filter 中的groupBy對數據進行分組。 然后你可以像這樣ctrl.checkList | groupBy: 'CheckListCategory'按類別過濾你的數據 ctrl.checkList | groupBy: 'CheckListCategory'

請看下面的演示或在這個小提琴中

我使用引導手風琴來顯示數據,但折疊也應該有效。 我不確定倒塌時它應該是什么樣子,這就是我使用手風琴的原因。

 angular.module('demoApp', ['ui.bootstrap', 'angular.filter']) .controller('MainController', MainController); function MainController($http, $scope) { var vm = this; $http.jsonp('http://www.mocky.io/v2/56183175100000e5387222f9?callback=JSON_CALLBACK').then(function(response) { console.log(response); vm.checkList = response.data[0].CheckList; }); }
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.14.0/ui-bootstrap-tpls.js"></script> <script src="https://cdn.rawgit.com/a8m/angular-filter/master/dist/angular-filter.js"></script> <div ng-app="demoApp" ng-controller="MainController as ctrl"> <uib-accordion> <uib-accordion-group heading="{{cat[0].CheckListCategory}}" ng-repeat="cat in ctrl.checkList | groupBy: 'CheckListCategory'"> <ul> <li ng-repeat="item in cat"> {{item.CheckListItem}} </li> </ul> </uib-accordion-group> </uib-accordion> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM