0

我有带有 nsdictionary 对象的数组,例如:

({"someKey" = "title";
  "name" = "someName";
 },
 {"someKey" = "title";
  "name" = "anotherName";
 }
 {"someKey" = "newTitle";
  "name" = "someName";
 }
)

请帮我以这种格式对其进行排序:

({"someKey" = "title";
  "names": (
    {"name" = "someName"},
    {"name" = "anotherName"}
  )
 },
 {"someKey" = "newTitle";
  "names": (
   {"name" = "someName"}
  )
 }
)

谢谢..

4

3 回答 3

1

据我从您的问题中了解到,您想将单个对象选择到一个字典对象中。

NSArray *yourArray=.... /* array which contains this data: ({"someKey" = "title";
  "name" = "someName";
 },
 {"someKey" = "title";
  "name" = "anotherName";
 }
)*/
NSMutableDictionary *newDictionary=[[NSMutableDictionary alloc]init];

for(int i=0;i<[yourArray count];i++){
    [newDictionary setObject:[yourArray objectAtIndex:i] forKey:@"names"];
}
于 2012-10-17T15:17:26.470 回答
0

你只需要遍历当前结构并构建一个以标题为唯一键的新字典:

NSEnumerator* arrayEnumerator = [myArray objectEnumerator];

NSDictionary* = dictFromArray;

NSMutableArray* titleArray = [[NSMutableArray alloc] init];
NSMutableDictionary* titleDict = [[NSMutableDictionary alloc] init];

while(dictFromArray = [arrayEnumerator nextObject])
{
    currentTitle = [dictFromArray objectForKey:@"someKey"];
    currentName = [dictFromArray objectForKey:@"name"];

    if([titles containsObject:currentTitle)
    {
    NSMutableDictionary namesArray = [titleDict objectForKey:currentTitle];
    [namesArray addObject:currentName];
    }
    else
    {
        [titles addObject:currentTitle];
        [titleDict addObject:[NSMutableArray arrayWithObject:currentName] forKey:currentTitle];
    }
}

这应该会给你一个看起来像这样的字典:

{
    title = 
    (
        someName,
        anotherName
    );

    newTitle = 
    (
        someName
    )
}

为了获得上面的确切结构,我认为这应该可行:

NSArray* titleKeys = [titleDict allKeys];

NSEnumerator* keyEnumerator = [titleKeys objectEnumerator];
NSMutableArray* finalArray = [[NSMutableArray alloc] init];
NSString* key;

while (key = [keyEnumerator nextObject])
{
    [finalArray addObject: [NSDictionary 
        dictionaryWithObjects:(key, [dictArray objectForKey:key])
        forKeys:(@"someKey", @"names")]];
}           
于 2012-10-18T21:00:50.447 回答
0
 ({"someKey" = "title";
 "name" = "someName";
 },
   {"someKey" = "title";
  "name" = "anotherName";
 }
)

假设以上等价于

NSArray *array=[NSArray arrayWithObjects:dictionary1,dictionary2,nil];

然后达到以下结果

  (
{
 "someKey" = "title";
"names": (
 {"name" = "someName"},
{"name" = "anotherName"}
  )
 }
)

我们有这个:

 //Get name array 
 NSMutableArray *names=[NSMutableArray array];

 for(int i=0;i<[array count];i++)
 {
     NSDictionary *dictionary=[array objectAtIndex:i];
     [names addObject:[dictionary valueForKey:@"name"];
 }


 NSDictionary *newDictionary=[NSDictionary dictionaryWithOjbectsAndKeys:@"someKey",@"title",names,@"names",nil];

//Your final result is an array with one object ( A Dictionary )

NSArray *finalArray=[NSArray arrayWithObjects: newDictionary,nil];
于 2012-10-17T15:35:02.113 回答