通过另一个值检索JSON对象的属性?

时间:2017-03-20 09:56:03

标签: angularjs json

My Angular脚本是 -

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

 $scope.set = [{"minValue":"30","ord":"414"}, {"minValue":"60","ord":"503"}, {"minValue":"90","ord":"541"}];

});

如果我发现最小值是60,那么我想找到序数(ord)吗?

3 个答案:

答案 0 :(得分:0)

您可以使用javascript find原型函数来查找并返回数组中的对象

 $scope.minVal = "60"
 $scope.set = [{"minValue":"30","ord":"414"}, {"minValue":"60","ord":"503"}, {"minValue":"90","ord":"541"}];

 $scope.obj = $scope.set.find(o => o.minValue === $scope.minVal);

 console.log( $scope.obj.ord )

演示

angular.module("app",[])
.controller("ctrl",function($scope){
 $scope.minVal = "60"
 $scope.set = [{"minValue":"30","ord":"414"}, {"minValue":"60","ord":"503"}, {"minValue":"90","ord":"541"}];
 
 $scope.obj = $scope.set.find(o => o.minValue === $scope.minVal);
 
 console.log( $scope.obj.ord )
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 
</div>

答案 1 :(得分:0)

取决于你想要的地方,即

1)如果您只想对控制器逻辑进行过滤,然后将该值用作单独的变量/范围变量,那么您只需使用javascript find函数

//Say simply you have target 'minValue' in a variable
$scope.searchValue = '60';
var result = $scope.set.find(function(v){return v.minValue == $scope.searchValue});
//it will return the array of all data with 'minValue == 60 ' in your case

//So in your case the actual value you want would be 
console.log(result.ord);

2)如果您只是想在html中过滤ng-repeat,那么您可以使用'filter'

<div ng-repeat="item in set | filter : {'minValue': searchValue}">
</div>

答案 2 :(得分:0)

您可以使用ES5中提供的filter方法

angular.module("app", [])
  .controller("ctrl", function($scope) {
    $scope.minVal = "60"
    $scope.set = [{
      "minValue": "30",
      "ord": "414"
    }, {
      "minValue": "60",
      "ord": "503"
    }, {
      "minValue": "90",
      "ord": "541"
    }];

    $scope.obj = $scope.set.filter(function(val) {
      return val.minValue === $scope.minVal;
    });

    console.log($scope.obj)
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">

</div>