[英]Create dictionary with dictionaries of arrays (sorted by a specific custom object property)?
标题可能会造成混淆,抱歉。 也许有人可以给我建议一个更合适的标题。
我有一个.json
文件,结构如下。
"sections": [{
"title": "Locations",
"key": "location"
}],
"contacts": [{
"title": "Social Worker",
"name": "Mrs X",
"office": "xxxxxxxx",
"location": "Lisburn",
"department": "xxxxxxxx",
"telephone": "xxx xxxxxxxx"
},...
解析时,我创建了一个名为contactsArray
的array
。 然后可以从该array
创建AEContact
对象,如下所示:
for (NSDictionary *contactDic in [contactsArray valueForKey:@"contacts"]) {
// Create AEContact objects
_contact = [[AEContact alloc] initWithDictionary:contactDic];
[contacts addObject:_contact];
}
self.contacts = [contacts copy];
在self.contacts
array
,该value
为contact.location
属性是什么,我很感兴趣,我需要建立单独的arrays
相关的AEContact
基于对象location
属性,然后将这些映射到location
key
在我的contactArray
dictionary
到目前为止,这是我尝试过的:
NSMutableDictionary *locationsDic = [NSMutableDictionary new];
// Loop through contacts
for (int i = 0; i < self.contacts.count; i++) {
// Sort by location
if ([self.contacts[i] valueForKey:@"location"] == [[[contactsArray valueForKey:@"contacts"] objectAtIndex:i] valueForKey:@"location"]) {
[locationsDic setValue:self.contacts[i] forKey:[[[contactsArray valueForKey:@"contacts"] objectAtIndex:i] valueForKey:@"location"]];
}
}
输出为:
{
Ballynahinch = "<AEContact: 0x15dda1fc0>";
Bangor = "<AEContact: 0x15dda2210>";
Lisburn = "<AEContact: 0x15dda1c70>";
...
}
当AEContact
对象具有相同location
,它将其设置为字典中的另一个键/值,并覆盖上一个条目。 我需要做的是这样的:
{
Lisburn = "<AEContact: 0x15dda18f0>",
"<AEContact: 0x15dda18f0>",
"<AEContact: 0x15dda18f0>";
Bangor = "<AEContact: 0x15dda18f0>",
"<AEContact: 0x15dda18f0>",
"<AEContact: 0x15dda18f0>";
}
我不确定输出是否应该/应该像上面的预览一样,我只能假设我尚未实现目标。 如何在array
创建相关的AEContact
对象并将它们映射到我的locationsDic
location
键? 谢谢。
标题(和问题描述)有点难以理解,但是我认为您正在尝试通过位置参数索引(AEContact)对象的数组。
我们可以通过更严格的命名以及在处理输入时使用查找或创建模式来澄清这一点。
NSDictionary *jsonResult = // the dictionary you begin with
NSArray *contactParams = jsonResult[@"contacts"];
NSMutableDictionary *contactsByLocation = [@{} mutableCopy];
for (NSDictionary *contactParam in contactParams) {
NSString *location = contactParam[@"location"];
// here's the important part: find the array of aecontacts in our indexed result, or
// create it if we don't find it
NSMutableArray *aeContacts = contactsByLocation[location];
if (!aeContacts) {
aeContacts = [@[] mutableCopy];
contactsByLocation[location] = aeContacts;
}
AEContact *aeContact = [[AEContact alloc] initWithDictionary:contactParam];
[aeContacts addObject:aeContact];
}
contactsByLocation
将是我认为您要寻找的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.