[英]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.