问题
I have the following multi-dimensional array (stripped and reduced for clarity)
[
{
"type": "type1",
"docs": [
{
"language": "EN"
},
{
"language": "DE"
},
{
"language": "EN"
}
]
},
{
"type": "type2",
"docs": [
{
"language": "EN"
}
]
},
{
"type": "type3",
"docs": [
{
"language": "FR"
},
{
"language": "DE"
},
{
"language": "DE"
}
]
}
]
I want to filter it, so only docs objects with a language of DE are shown. In other words, I need this:
[
{
"type": "type1",
"docs": [
{
"language": "DE"
}
]
},
{
"type": "type2",
"docs": []
},
{
"type": "type3",
"docs": [
{
"language": "DE"
},
{
"language": "DE"
}
]
}
]
My array is initially created by the following piece of code:
NSMutableArray *docsArray;
[self setDocsArray:[downloadedDocsArray mutableCopy]];
I have tried looping the array and removing unwanted objects. I have tried looping the array and copying wanted objects to a new array. I have tried using NSPredicate instead of looping, all of which had very little success.
Can anyone point me in the right direction?
Thanks in advance.
回答1:
You should iterate over the array to get the dictionaries containing the arrays to filter:
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];
}
来源:https://stackoverflow.com/questions/14263479/how-to-filter-a-multi-dimensional-array