我有NSArray
个NSDictionaries
。我想创建一个具有相同数量NSArray
的新NSDictionaries
,但我只想要字典中的一些键,而不是所有键。
示例:
Array有2个词典。每个字典都有密钥name, age, address, email, phone
。
我想要新的数组,它也有2个词典,但只有name and address
个键。
答案 0 :(得分:1)
我会做类似的事情:
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];
}
];
答案 1 :(得分:0)
尝试以下操作(与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
答案 2 :(得分:0)
试试这个
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];
}