使用 NSPredicate 仅从字典数组中获取特定键的值 [英] Using NSPredicate get only values of a particular key from an array of dictionaries

查看:52
本文介绍了使用 NSPredicate 仅从字典数组中获取特定键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这些值.我只知道钥匙.

I do not know the values. I only know the key.

arrTripCat : 
(
    { tripcategory = "general_tourism"; },
    { tripcategory = nightlife; },
    { tripcategory = "art_museums"; },
    { tripcategory = nightlife; },
    { tripcategory = architecture; },
    { tripcategory = nightlife; }
);

我尝试过的 NSPredicate :

NSArray *arrTripCat = [NSArray arrayWithArray:[self.dictSearchResult objectForKey:@"TripCategories"]];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF.@allKeys contains[cd] %@",@"tripcategory"];

NSMutableArray *filteredArray = [[NSMutableArray alloc] init];
[filteredArray addObjectsFromArray:[arrTripCat filteredArrayUsingPredicate:predicate]];

在此之后,filteredArray 仍然具有与以前相同格式的所有数据.

after this, the filteredArray still has all of the data in the same format as before.

filteredArray:
(
    { tripcategory = "general_tourism"; },
    { tripcategory = nightlife; },
    { tripcategory = "art_museums"; },
    { tripcategory = nightlife; },
    { tripcategory = architecture; },
    { tripcategory = nightlife; }
);

我希望得到的最终结果是将 tripcategory 键的所有值放入一个数组中.即

The end result I'm looking to get is to have all of the values for the tripcategory key put into an array. i.e.

 ( general_tourism, nightlife, art_museums, architecture )

推荐答案

您不想过滤,而是想折叠结果,因此使用谓词不能满足您的目的.在纯可可中,您可以:

You don't want to filter, you want to fold the results, so using a predicate doesn't serve your purpose. In plain Cocoa, you can do:

NSMutableArray *results = @[].mutableCopy;
for (NSDictionary *dict in arrTripCat) {
   [results addObject:dict[@"tripcategory"];
}

这将为您提供(一般旅游、夜生活、艺术博物馆、建筑).

This will give you ( general_tourism, nightlife, art_museums, architecture ).

这篇关于使用 NSPredicate 仅从字典数组中获取特定键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆