如何使用角度js从json获取唯一值?

时间:2017-02-12 09:53:07

标签: angularjs json parsing

回复代码: 在这个回复中,eid重复了,但我只想显示一次。

{"response": [
        {
            "sid": 1,
            "eid": "AA",
            "ename": "AA11"
          },{
            "sid": 2,
            "eid": "AA",
            "ename": "AA11"
          }
    ],
    "status": "success"
}

2 个答案:

答案 0 :(得分:0)

There is no magic way. This task should primarily be completed before the response lands the client (on server).

What you can do is make a function which handles the response the way you prefer.

e.g.

  //Removes duplicates of eid property
    function getUniqueValues(input) {
        var output = [];

        function existsInOutput(element) {
            return output.map(function(val) {
                return val.eid
            }).includes(element.eid)
        };

        angular.forEach(input,function(val, key) {
            if (!existsInOutput(val)) {
                output.push(val);
            }
        })

        return output;
    }

答案 1 :(得分:0)

您可以使用 unique

中的 AngularUI 过滤器
<p ng-repeat="x in data.response | unique: 'ename'">{{x.ename}}</p>

<强>样本

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui/0.4.0/angular-ui.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
    <p ng-repeat="x in data.response | unique: 'ename'">{{x.ename}}</p>
<script>
//App declaration
var app = angular.module('myApp',['ui.filters']);
//Controller Declaration
app.controller('myCtrl',function($scope){
    $scope.data = {"response": [
        {
            "sid": 1,
            "eid": "AA",
            "ename": "AA11"
          },{
            "sid": 2,
            "eid": "AA",
            "ename": "AA11"
          }
    ],
    "status": "success"
};
});
</script>
</body> 
</html>