我是棱角分明的新手。我有一个链接http://www.bursamalaysia.com/searchbox_data.json,我希望获得一个名称和ID列表。
我能够从json中的链接获取列表,但我需要过滤列表中不需要的项目。如果id超过4位,则删除full_name,name,short_name和id。例如:如果id:123456,则需要将其与名称,短名称一起过滤掉。
app.js
abc: {
name: "Momo",
value: "kls",
long: "KLSE",
searchRef: KLSE_SEARCH_REF,
searchRefURL: "http://www.bursamalaysia.com/searchbox_data.json",
},
details.js
$ionicLoading.show();
if ($scope.currentMarket == "abc"){
$webServicesFactory.getNotParsed($marketProvider[$scope.currentMarket].searchRefURL).then(function success(response){
response = JSON.parse(response);
for (var i = 0; i < response[0].length; i++){
$scope.searchRef.push({
name: response[0][i].name || response[0][i].full_name,
symbol: response[0][i].short_name,
code: response[0][i].id,
market: $marketProvider[$scope.currentMarket].long
});
}
console.info($scope.searchRef);
$ionicLoading.hide();
});
}
HTML
<div class="list">
<div class="item" ng-repeat="item in searchItems" ng-click="openDetail(item)">
<p>{{item.symbol}} - {{item.name}}</p>
<p>{{currentMarket | uppercase}}</p>
</div>
</div>
答案 0 :(得分:1)
你可以使用Array.prototype.filter
和Array.prototype.map
,这非常优雅。
$ionicLoading.show();
if($scope.currentMarket == "abc") {
$webServicesFactory.getNotParsed($marketProvider[$scope.currentMarket].searchRefURL).then(
function success(response) {
$scope.searchRef = JSON.parse(response)[0].filter(function(itm) {
// whatever you want to filter should pass this condition
return itm.id.toString().length <= 3;
}).map(function(itm) {
// for each item, transform to this
return {
name: itm.name || itm.full_name,
symbol: itm.short_name,
code: itm.id,
market: $marketProvider[$scope.currentMarket].long
};
});
$ionicLoading.hide();
}
);
}
确保处理任何错误并使您的代码具有防御性。
答案 1 :(得分:0)
如果您需要过滤超过4位数的ID值,那么您可以使用简单条件限制if(response[0][i].id <= 999)
以下示例:
for(var i=0; i<response[0].length; i+=1){
if(response[0][i].id.toString().length <= 3 ) {
$scope.searchRef.push(
{
name: response[0][i].name || response[0][i].full_name,
symbol: response[0][i].short_name,
code: response[0][i].id,
market: $marketProvider[$scope.currentMarket].long
}
);
}
}