Jon
Jon

Reputation: 4732

How to modify array of dictionaries?

I have an NSArray with several NSDictionaries. I want to create a new NSArray with the same number of NSDictionaries but I only want some keys in the dictionary, not all of the ones.

Example:

Array has 2 dictionaries. Each dictionary has key name, age, address, email, phone.

I want new array that also has the 2 dictionaries, but only the name and address keys.

Upvotes: 1

Views: 137

Answers (3)

yuji
yuji

Reputation: 16725

I'd do something like:

NSMutableArray *replacementArray = [NSMutableArray array];

[existingArray enumerateObjectsUsingBlock:
    ^(NSDictionary *dictionary, NSUInteger idx, BOOL *stop)
    {
         NSDictionary *newDictionary = [NSDictionary dictionaryWithObjectsAndKeys:[dictionary objectForKey:@"name"], @"name", [dictionary objectForKey:@"address"], @"address", nil];
         [replacementArray addObject:newDictionary];
    }
];

Upvotes: 1

rakeshNS
rakeshNS

Reputation: 4257

Try this

 for(i=0;i<[firstArray count];i++){

 NSArray *objectArray=[NSArray arrayWithObjects:[[firstArray objectAtIndex:i]objectForKey:@"name"],[[firstArray objectAtIndex:i]objectForKey:@"address"]];

 NSArray *keyArray=[NSArray arrayWithObjects:@"name",@"address"];
 NSDictionary *myDictionary=[NSDictionary dictionaryWithObjects:objectArray forKeys:keyArray];

 [secondArray addObject:myDictionary];
}

Upvotes: 0

jrtc27
jrtc27

Reputation: 8526

Try the following (compatible with iOS 2+):

NSMutableArray *newArray = [NSMutableArray array];
for (NSDictionary *origDict in origArray) { // Replace origArray with your array's name
    [newArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:[origDict objectForKey@"name"], @"name", [origDict objectForKey@"address"], @"address", nil]];
}
NSArray *newImmutableArray = [newArray copy] // If you want to ensure your array is not mutable
// ...
[newImmutableArray release]; // To balance -copy above

Upvotes: 0

Related Questions