How to filter a multi-dimensional array

筅森魡賤 提交于 2019-12-12 05:43:12

问题


I have the following multi-dimensional array (stripped and reduced for clarity)

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

I want to filter it, so only docs objects with a language of DE are shown. In other words, I need this:

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

My array is initially created by the following piece of code:

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

I have tried looping the array and removing unwanted objects. I have tried looping the array and copying wanted objects to a new array. I have tried using NSPredicate instead of looping, all of which had very little success.

Can anyone point me in the right direction?

Thanks in advance.


回答1:


You should iterate over the array to get the dictionaries containing the arrays to filter:

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];
}


来源:https://stackoverflow.com/questions/14263479/how-to-filter-a-multi-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!