2013-02-14 63 views
0

嵌套意味着采用一组键值对并按指定键分层分组。请参阅此页面中的示例:http://bl.ocks.org/d/3176159/。如果不是的话,我只会尝试移除https://github.com/mbostock/d3/blob/master/src/core/nest.js,但我不想重新发明轮子。Objective-C中是否有类似D3的Nest功能?

+0

如果我们没有必须去通过代码试图找出它做什么,因为你**告诉它我们这将是有益的。** – 2013-02-14 06:08:18

+0

好一点!我添加了一些解释和例子的链接。 – 2013-02-14 06:11:27

+0

谢谢!那么,为了记录,我不知道这一切立即做到。但是,您可以很容易地重新实现它。 – 2013-02-14 06:21:49

回答

0

这是我想出来的答案。如果您有改进建议,请告诉我。

// Wrapper method 
// keys are in order of hierarchy 
- (NSMutableArray *)nestArray:(NSArray *)array withKeys:(NSArray *)keys 
{ 
    return [self nestArray:array withKeys:keys depth:0]; 
} 

// Private 
// Assumes arrays of dictionaries with strings as the entries. 
- (NSMutableArray *)nestArray:(NSArray *)array withKeys:(NSArray *)keys depth:(int)depth 
{ 
    // Current key 
    NSString *key = [keys objectAtIndex:depth]; 
    depth++; 

    // Create dictionary of the keys 
    NSMutableDictionary *map = [[NSMutableDictionary alloc] init]; 
    for (NSDictionary *dictionary in array) { 
     NSString *value = [dictionary objectForKey:key]; 
     if ([map objectForKey:value]) { 
      [[map objectForKey:value] addObject:dictionary]; 
     } else { 
      [map setObject:[NSMutableArray arrayWithObject:dictionary] forKey:value]; 
     } 
    } 

    NSMutableArray *nest = [[NSMutableArray alloc] init]; 
    for (NSString *valkey in [map allKeys]) { 
     NSMutableArray *values = [map objectForKey:valkey]; 
     if (depth < keys.count) { 
      values = [self nestArray:[NSArray arrayWithArray:array] withKeys:keys depth:depth]; 
     } 
     NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:valkey,@"key",values,@"values", nil]; 
     [nest addObject:dictionary]; 
    } 

    return nest; 
} 
相关问题