2017-06-20 145 views
0

我是新来的角js。我有一个链接http://www.bursamalaysia.com/searchbox_data.json,我想获得名称和ID列表。javascript来过滤不需要的数据

我能够从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

你尝试过什么吗?您可以使用基本的Javascript条件检查轻松完成此操作。 – Hoyen

+1

你可以使用'Array.prototype.filter'和'Array.prototype.map' – Mirodil

+0

@Miro你能详细解释一下吗? – bkcollection

回答

1

您可以用Array.prototype.filterArray.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(); 
     } 
    ); 
    } 

确保处理任何错误并使您的代码具有防御性。

+0

对于性能而言,这应该比向范围内的数组多次推送更好,因为Angular digest循环只触发一次。 – Hinrich

0

,如果你需要过滤MOR Ë超过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 
     } 
    ); 
    } 
    } 
+0

'if(response [0] [i] .id <= 999)'是保留4位还是删除4位?我想删除超过4位数字 – bkcollection

+0

是的,如果id低于或等于999,那么只有条件将为真,并将对象推送到$ scope.searchRef数组变量。所以$ scope.searchRef有其余的值超过4位数的id值 –

+0

它可以使用ID的长度吗?请指教。一些id是'3074LA',它不是一个数字 – bkcollection