简体   繁体   中英

How to query a JSON object

In my AngularJS web app, How can I query a JSON object ?

For example in the below JSON object how can I find the value of reportTypeLabel where reportTypeId=3

JSON:

[  
   {  
      reportTypeId:5,
      reportTypeCode:"FINREP",
      reportTypeLabel:"Financial Reporting"
   },
   {  
      reportTypeId:9000002,
      reportTypeCode:"REM HE",
      reportTypeLabel:"High Earners"
   },
   {  
      reportTypeId:3,
      reportTypeCode:"COREP LE",
      reportTypeLabel:"Large Exposures - COREP"
   }
]

You can require $filter service and do

var elements = $filter('filter')(arrayOfObjects,{reportTypeId: 3});

elements will be an array of all the elements with that 'reportTypeId' i would recommend reading about angular filters and https://docs.angularjs.org/api/ng/service/ $filter

If you're going to use data manipulation extensively, I'd highly recommend using a JS library, like underscore or lodash .

For example, using underscore :

// assuming your object is called data

var result = _.findWhere(data, {
    reportTypeId: 3
}).reportTypeLabel;
// result === 'Large Exposures - COREP'

You could do this

<div ng-repeat="report in reports | filter:{reportTypeId:'3'}">
    {{report.reportTypeCode}}
</div>

Working Fiddle

You can use regular filter function on array:

var items = [
  {reportTypeId:5, reportTypeCode:"FINREP"},
  {reportTypeId:9000002, reportTypeCode:"REM HE"}
];
var onlyMatching = items.filter(function(item){ return item.reportTypeId == 3; });

Or an angular filter in html

<div ng-repeat="item in items | filter: {reportTypeId: '3'}">{{item. reportTypeLabel}}</div>

Or an angular filter through $filter service

module.controller('ItemsCtrl', function($filter){
  $scope.filtered = $filter('filter')($scope.items,{ reportTypeId: '3' });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM