2017-06-20 49 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

相關問題