如何过滤多维数组

时间:2013-01-10 17:15:10

标签: objective-c multidimensional-array filter nspredicate

我有以下多维数组(为了清晰起见而剥离和缩小)

[
    {
        "type": "type1",
        "docs": [
            {
                "language": "EN"
            },
            {
                "language": "DE"
            },
            {
                "language": "EN"
            }
        ]
    },
    {
        "type": "type2",
        "docs": [
            {
                "language": "EN"
            }
        ]
    },
    {
        "type": "type3",
        "docs": [
            {
                "language": "FR"
            },
            {
                "language": "DE"
            },
            {
                "language": "DE"
            }
        ]
    }
]

我想过滤它,因此只显示语言为DE的docs对象。换句话说,我需要这个:

[
    {
        "type": "type1",
        "docs": [
            {
                "language": "DE"
            }
        ]
    },
    {
        "type": "type2",
        "docs": []
    },
    {
        "type": "type3",
        "docs": [
            {
                "language": "DE"
            },
            {
                "language": "DE"
            }
        ]
    }
]

我的数组最初是由以下代码创建的:

NSMutableArray *docsArray;
[self setDocsArray:[downloadedDocsArray mutableCopy]];

我试过循环数组并删除不需要的对象。我已经尝试循环数组并将所需对象复制到新数组。我尝试过使用NSPredicate而不是循环,所有这些都没有取得什么成功。

有人能指出我正确的方向吗?

提前致谢。

1 个答案:

答案 0 :(得分:3)

您应该遍历数组以获取包含要过滤的数组的字典:

NSArray* results;
NSMutableArray* filteredResults= [NSMutableArray new]; // This will store the filtered items
// Here you should have already initialised it 
for( NSDictionary* dict in results)
{
    NSMutableDictionary* mutableDict=[dict mutableCopy];
    NSArray* docs= dict[@"docs"];
    NSPredicate* predicate= [NSPredicate predicateWithFormat: @"language like 'DE'"];
    docs= [docs filteredArrayUsingPredicate: predicate];
    [mutableDict setObject: docs forKey: @"docs"];
    [filteredResults addObject: mutableDict];
}