使用数组字典创建字典(按特定自定义 object 属性 排序)?

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"
             },...

解析时,我创建了一个名为 contactsArrayarray。然后我可以从这个 array 创建 AEContact objects,如下所示:

    for (NSDictionary *contactDic in [contactsArray valueForKey:@"contacts"]) {
    // Create AEContact objects
    _contact = [[AEContact alloc] initWithDictionary:contactDic];
    [contacts addObject:_contact];
}
self.contacts = [contacts copy];

self.contactsarray中,contact.location属性的value是我感兴趣的,我需要单独创建arrays 的相关 AEContact object 基于 location 属性,然后将它们映射到我的 [=31] 中的 location key =] 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 object 具有相同的 location 时,它会将其设置为字典中的另一个 key/value 并覆盖之前的条目。我需要发生的事情是这样的:

{
    Lisburn = "<AEContact: 0x15dda18f0>",
              "<AEContact: 0x15dda18f0>",
              "<AEContact: 0x15dda18f0>";

    Bangor = "<AEContact: 0x15dda18f0>",
             "<AEContact: 0x15dda18f0>",
             "<AEContact: 0x15dda18f0>";
}

我不确定输出是否应该 should/will 看起来像上面的预览,我只能假设,因为我还没有实现我的目标。如何在 array 中创建相关的 AEContact object 并将它们映射到我的 locationsDic 中的 location 键?谢谢。

标题(和问题描述)有点难以理解,但我认为您正在尝试通过其位置参数为 (AEContact) objects 的数组编制索引。

我们可以在处理输入时使用更严格的命名和 find-or-create 模式来澄清这一点。

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 将是我认为您正在寻找的。