我正在尝试通过自定义过滤器从 JSON 响应中返回唯一值。
数据:
[
{
"SHFUserID": "400",
"AlertID": "12",
"TickerID": "4512",
"Ticker": "GOOG",
"Active": "1",
"Status": "2"
},
{
"SHFUserID": "400",
"AlertID": null,
"TickerID": "4512",
"Ticker": "GOOG",
"Active": null,
"Status": null
},
{
"SHFUserID": "400",
"AlertID": null,
"TickerID": "10190",
"Ticker": "IBM",
"Active": null,
"Status": null
}
]
筛选:
.filter('uniqueTickers', function() {
return function(tickers) {
var tags = {};
angular.forEach(tickers, function(obj) {
if(!(obj.Ticker in tags)){
tags[obj.Ticker] = {id: obj.TickerID, name:obj.Ticker}
if(!tags[obj.Ticker].pending){
tags[obj.Ticker].pending = 0;
}
if(!tags[obj.Ticker].settled){
tags[obj.Ticker].settled = 0;
}
if(!tags[obj.Ticker].order){
tags[obj.Ticker].order = 3;
}
}
if(obj.Status === "1"){
tags[obj.Ticker].pending = 1;
if(tags[obj.Ticker].order > 2){
tags[obj.Ticker].order = 2;
}
}
if(obj.Status === "2"){
tags[obj.Ticker].settled = 1;
if(tags[obj.Ticker].order > 1){
tags[obj.Ticker].order = 1;
}
};
});
return tags;
};
html:
Search: <input ng-model="query">
Sort by:
<select ng-model="orderProp">
<option value="name">Alphabetical</option>
<option value="order">Alert Status</option>
</select>
<ul class="tickerList">
<li ng-repeat="ticker in tickers | filter:query | orderBy:orderProp | uniqueTickers">
<a href="#/ticker/{{ticker.id}}">{{ticker.name}}</a>
<p>{{ticker}}</p>
</li>
</ul>
但结果看起来像:
GOOG
{"id":"4512","name":"GOOG","pending":0,"settled":0,"order":3}
IBM
{"id":"10190","name":"IBM","pending":0,"settled":0,"order":3}
代替:
GOOG
{"id":"4512","name":"GOOG","pending":0,"settled":1,"order":1}
IBM
{"id":"10190","name":"IBM","pending":0,"settled":0,"order":3}
目标是保持结果集的唯一性,但如果该代码的任何记录处于未决或已结算,则将“待处理”或“已结算”设置为 true。