Reputation: 1044
I have an app that gathers a users data via JSON. After putting the data into an array, I want to get how many different values occur for a certain key, not how many times is appears.
Example.
I gather restaurant data the user has assembled on a site. His JSON data spits out a key for genre: 6 Pizza places, 4 Chinese places, and 2 Mexican places that he has "liked". So there are 3 different values for the genre key, but they occur x amount of times. I want to be able to see how many different values for genre there are, not how many times they occur, which can get via NSCountedSet once I get the values for genre.
I'm having trouble wrapping my head around how to do this without hard coding in every possibility.
Thanks!
Upvotes: 0
Views: 167
Reputation: 6396
Assuming a format like:
[
{
"Restaurant":"McDonalds",
"Genre":"Vomit"
},
{
"Restaurant":"Wendys",
"Genre":"Gross"
},
{
"Restaurant":"Chipotle",
"Genre":"Delish"
},
{
"Restaurant":"White Castle",
"Genre":"Gross"
}
]
You could do the following:
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonInDataForm options:kNilOptions error:&error];
NSMutableArray *types = [[NSMutableArray alloc] init];
for(NSDictionary *restaurant in jsonArray)
{
if(![types containsObject:[restaurant objectForKey:@"Genre"]])
[types addObject:[restaurant objectForKey:@"Genre"]];
}
int numberOfGenres = [types count];
Upvotes: 1