2013-01-10 48 views
0

我有以下多維陣列(剝離並減小爲清楚起見)如何過濾多維陣列

[ 
    { 
     "type": "type1", 
     "docs": [ 
      { 
       "language": "EN" 
      }, 
      { 
       "language": "DE" 
      }, 
      { 
       "language": "EN" 
      } 
     ] 
    }, 
    { 
     "type": "type2", 
     "docs": [ 
      { 
       "language": "EN" 
      } 
     ] 
    }, 
    { 
     "type": "type3", 
     "docs": [ 
      { 
       "language": "FR" 
      }, 
      { 
       "language": "DE" 
      }, 
      { 
       "language": "DE" 
      } 
     ] 
    } 
] 

欲過濾它,所以只有文檔與DE的語言對象被示出。換句話說,我需要這樣的:

[ 
    { 
     "type": "type1", 
     "docs": [ 
      { 
       "language": "DE" 
      } 
     ] 
    }, 
    { 
     "type": "type2", 
     "docs": [] 
    }, 
    { 
     "type": "type3", 
     "docs": [ 
      { 
       "language": "DE" 
      }, 
      { 
       "language": "DE" 
      } 
     ] 
    } 
] 

我的陣列最初由下面的代碼段創建的:

NSMutableArray *docsArray; 
[self setDocsArray:[downloadedDocsArray mutableCopy]]; 

我試圖循環陣列和除去不需要的對象。我嘗試循環數組並將想要的對象複製到新數組。我嘗試過使用NSPredicate而不是循環,所有這些都很少成功。

任何人都可以指向正確的方向嗎?

在此先感謝。

+0

這個數組是否包含詞典? –

+0

如果你只想看* DE *的語言,爲什麼你期望結果中的'type2'? – holex

回答

3

你應該迭代這個數組獲取包含數組的字典進行過濾:

NSArray* results; 
NSMutableArray* filteredResults= [NSMutableArray new]; // This will store the filtered items 
// Here you should have already initialised it 
for(NSDictionary* dict in results) 
{ 
    NSMutableDictionary* mutableDict=[dict mutableCopy]; 
    NSArray* docs= dict[@"docs"]; 
    NSPredicate* predicate= [NSPredicate predicateWithFormat: @"language like 'DE'"]; 
    docs= [docs filteredArrayUsingPredicate: predicate]; 
    [mutableDict setObject: docs forKey: @"docs"]; 
    [filteredResults addObject: mutableDict]; 
} 
+0

感謝您的迴應,但我收到以下錯誤消息:'NSDictionary'沒有可見的@interface聲明選擇器'setObject:forKey:' – Typhoon101

+0

我也在控制檯中看到以下錯誤。 **終止應用程序,由於未捕獲的異常'NSInternalInconsistencyException',原因:' - [__ NSCFDictionary setObject:forKey:]:發送到不可變對象的變異方法' – Typhoon101

+0

你是對的,字典是不可變的。您需要將所有數據存儲在可變字典中。 –