Get specific data field from NSDictionarys nested in NSArray
-
27-10-2019 - |
Question
I have a array with nested dictionary data like this:
[{ link : [
{ $ref: "foo", $href: "first_foo"},
{ $ref: "bar", $href: "barrrrrrr"},
{ $ref: "quz", $href: "quzzzzzzz"}]},
{ link : [
{ $ref: "foo", $href: "second_foo"},
{ $ref: "bar", $href: "barrrrrrr"},
{ $ref: "quz", $href: "quzzzzzzz"}]}]
I want to pick out the foo
of each dictionary. The wanting result like this:
[{ foo: "first_foo"}, { foo: "second_foo"}]
I've tried using [myArray valueForKey @"@customFilterForFoo"]
, and implemented the customFilterForFoo
for category on NSDictionary, but this ends up with *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFArray 0x6b81a10> valueForUndefinedKey:]: this class is not key value coding-compliant for the key customFilterForFoo.'
How can i do something like this? Thanks!
Solution
You should loop in your array of dictionaries then in each one search for your foo's value :
NSMutableArray *arrayOfFooValues = [[NSMutableArray alloc] init];
for (NSDictionary *aDictionary in myArray) {
if ([aDictionary valueForKey @"foo"]!= nil) {
[arrayOfFooValues addObject:[aDictionary valueForKey @"foo"]];
}
}
if you want your "wanting result" you can use the setValue:forKey: method but since the result is an array of Foo's values, key value coding isn't necessary in all cases (unless you want to add something else in your array)