響應代碼: 在此響應eid重複,但我只想顯示一次。如何使用角js從json獲取唯一值?
{"response": [
{
"sid": 1,
"eid": "AA",
"ename": "AA11"
},{
"sid": 2,
"eid": "AA",
"ename": "AA11"
}
],
"status": "success"
}
響應代碼: 在此響應eid重複,但我只想顯示一次。如何使用角js從json獲取唯一值?
{"response": [
{
"sid": 1,
"eid": "AA",
"ename": "AA11"
},{
"sid": 2,
"eid": "AA",
"ename": "AA11"
}
],
"status": "success"
}
您可以使用unique
過濾器從AngularUI
<p ng-repeat="x in data.response | unique: 'ename'">{{x.ename}}</p>
DEMO
<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>
沒有神奇的方法。這個任務應該主要在響應登陸客戶端之前完成(在服務器上)。
你可以做的是做一個函數來處理你喜歡的方式。
例如
//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;
}
剛開g error:令牌「>」上的語法錯誤,無效FunctionExpressionHeader – user2709752
'angular.forEach(input,(val,key)'忘記添加'input'屬性。我編輯了我的答案。我也爲你製作了[小提琴](https://jsfiddle.net/ucs403kL/)。請檢查 – Korte
謝謝你,但日食顯示令牌「>」的錯誤 – user2709752
爲什麼downvote here? – Sajeetharan
謝謝Sajeetharan得到它 – user2709752