2016-08-05 33 views
2

我有SwityJson的問題,並刪除陣列的元素迅速刪除項目

對於進一步的數據處理我必須刪除一些元素。

這裏我的代碼

self.jsonObj = JSON(value) 

//Filtern 

for i in 0 ..< self.jsonObj["customer"].count { 

    if self.jsonObj["customer"][i]["Group_A"].string == "Mr Abcde" 
      || self.jsonObj["customer"][i]["Group_A"].string == "Mr Bcde" 
      || self.jsonObj["custome"][i]["Group_B"].string == "Mr Abcde" 
      || self.jsonObj["customer"][i]["Group_B"].string == "Mr Bcde" 
    { 
     self.jsonObj["customer"].arrayObject?.removeAtIndex(i) 
    } 
} 

現在的問題:如果運行的代碼不是所有找到的元素將被刪除。 我認爲循環遍歷所有元素太快了。沒有時間去除任務?! 我該如何處理它。循環......找到了......停止循環...刪除項...開始循環..

通過使if語句三次一切都很好的找到的所有元素被刪除,但嘿,這不是我想要的。

或者是有可能過濾數組然後說

filterdData = jsonObj 

回答

0

嘗試

  //Filtern 

for i in 0 ..< self.jsonObj["customer"].count { 
     let groupA = self.jsonObj["customer"][i]["Group_A"].string 
     let groupB = self.jsonObj["customer"][i]["Group_B"].string 

      if groupA == "Mr Abcde" || groupA == "Mr Bcde" || groupB == "Mr Abcde" || groupB == "Mr Bcde"{ 
        self.jsonObj["customer"].rawArray.removeAtIndex(i) 
      }     
} 

這不僅有JSON對象更少電話(可能挽救速度),但它也使用rawArray而不是arrayObject,它直接寫入數組而不是通過arrayObject到rawArray。

+0

對不起,這是相同的結果.. :( 不是所有發現的元素都刪除 – Marc

0

的問題是,你改變,從循環中終止循環計數。你必須這樣做,可能使用過濾器或相關的方法,而不是

0

我會建議修改之前標準化數據。但如果失敗,你可以試試這個:

let filteredJson = self.jsonObj["customer"].filter { elem in 
    !(["Mr Abcde", "Mr Bcde"].contains(elem.["Group_A"].string) || 
    ["Mr Abcde", "Mr Bcde"].contains(elem.["Group_B"].string)) 
} 

然後使用filteredJson常數。

+0

好主意,但我怎麼能過濾JSON到JSON格式? – Marc