简体   繁体   English

如何基于JSON中的另一个字典键过滤字典值?

[英]How to filter dictionary values based on another dictionary key from a JSON?

I have a table with a UISearchController that searches it. 我有一个带有UISearchController进行搜索的表。 The first table is populated from a JSON with a format of: 第一个表从JSON填充,格式为:

{
    "items":
        [
            {
                "title":"title1",
                "url":"url1",
            },

            {
                "title":"title2",
                "url":"url2",
            }
        ]
}

The "title" is shown as the cell's textLabel and the url is the link that opens when the cell is clicked. “标题”显示为单元格的textLabel,URL是单击该单元格时打开的链接。

When I search in the search bar a results table shows populated by the the titles that match the search criteria. 当我在搜索栏中搜索时,结果表将显示由符合搜索条件的标题组成的表。 My problem is these don't include the urls so nothing happens when these cells are clicked. 我的问题是这些不包含网址,因此单击这些单元格时什么也不会发生。 My search criteria is as follows: 我的搜索条件如下:

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {

    // filter the search results
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [cd] %@", self.searchController.searchBar.text];
    self.results = [[self.JSONarray valueForKey:@"title"] filteredArrayUsingPredicate:predicate];
    [self.tableView reloadData];

}

I can see what I think is the problem but cannot figure out how to fix it. 我可以看到我认为的问题,但无法找出解决方法。 When searching it is only searching through the titles and populating the results array with these but I need the urls to filter based on the corresponding titles. 在搜索时,仅搜索标题并使用这些标题填充结果数组,但是我需要根据相应标题过滤网址。

Any help would be really appreciated. 任何帮助将非常感激。

I'm typing this off the top of my head since I don't have all your code, but try the following: 由于没有您的所有代码,因此请在头顶上键入此内容,但请尝试以下操作:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title contains [cd] %@", self.searchController.searchBar.text];
self.results = [self.JSONarray filteredArrayUsingPredicate:predicate];

The difference is that we're not filtering on the title elements of the JSON array first; 不同之处在于我们不首先过滤JSON数组的title元素; instead, we're searching the whole array, and using title in the predicate. 相反,我们正在搜索整个数组,并在谓词中使用title

After doing this, self.results should be an NSArray of NSDictionary s, each of which contains a title and url element. 完成此操作后, self.results应该是NSDictionaryNSArray ,每个NSArray都包含一个titleurl元素。 So you can access the URLs as appropriate to retrieve your results. 因此,您可以适当地访问URL以检索结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM