0

嵌套意味着获取一组键值对并按指定的键对它们进行分层分组。有关示例,请参见此页面:http: //bl.ocks.org/d/3176159/。如果没有,我将尝试将https://github.com/mbostock/d3/blob/master/src/core/nest.js移植过来,但我不想重新发明轮子。

4

1 回答 1

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;
}
于 2013-02-14T18:55:50.437 回答