0

我有以下多维数组(为清楚起见,已剥离和缩减)

[
    {
        "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 而不是循环,所有这些都没有成功。

谁能指出我正确的方向?

提前致谢。

4

1 回答 1

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];
}
于 2013-01-10T18:31:33.417 回答