创建从字典数组中过滤的数组,并将数组作为输入

时间:2014-03-13 04:18:24

标签: ios objective-c nsarray nsdictionary

我有一个字典和一个数组,如下所示

词典:

{
    "value": [
        {
            "ctgid": "1",
            "catename": "tow"
        },
        {
            "ctgid": "2",
            "catename": "towrequest"
        },
        {
            "ctgid": "3",
            "catename": "electrical"
        },
        {
            "ctgid": "5",
            "catename": "plumber"
        },
        {
            "ctgid": "6",
            "catename": "maintenance"
        },
        {
            "ctgid": "7",
            "catename": "home"
        },
        {
            "ctgid": "8",
            "catename": "computer"
        },
        {
            "ctgid": "9",
            "catename": "1q2w"
        }
    ]
}

catename数组:

(
tow,
towrequest,
plumber
)

在Array.From上面有一个catename列表我想在上面的数组中创建与catename相关的ctgid数组。

所以我的最终输出应该是:

catgid数组:

(
1,
2,
5
)

注意:我可以使用循环播放,但我不想使用任何循环。

3 个答案:

答案 0 :(得分:4)

//Json data
NSString *jsonString = @"{\"value\":[{\"ctgid\":\"1\",\"catename\":\"tow\"},{\"ctgid\":\"2\",\"catename\":\"towrequest\"},{\"ctgid\":\"3\",\"catename\":\"electrical\"},{\"ctgid\":\"5\",\"catename\":\"plumber\"},{\"ctgid\":\"6\",\"catename\":\"maintenance\"},{\"ctgid\":\"7\",\"catename\":\"home\"},{\"ctgid\":\"8\",\"catename\":\"computer\"},{\"ctgid\":\"9\",\"catename\":\"1q2w\"}]}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
//Converting the data into NSDictionary
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

//Get the array of objects
NSArray *array = [NSArray arrayWithArray:[json objectForKey:@"value" ]];

//Category filter names
NSArray *filteCatename = [NSArray arrayWithObjects:@"tow",@"towrequest",@"plumber",nil];
//NSPreicate to filter the array using "in" constrain
NSArray *filtered = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(catename in %@)", filteCatename]];

您可以使用NSPredicate直接过滤NSArray而无需循环。

答案 1 :(得分:2)

现在为时已晚,尽管我给出了答案希望这可能有所帮助..

   [dictArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { //dictArray is an array contains your "value" 
       if([arrCatename containsObject:[obj objectForKey:@"catename"]]) //arrCatename is array contains catename list
        {
          [arrCatid addObject:[obj objectForKey:@"ctgid"]]; //arrCatid is the result
        }
   }];

  NSLog(@"%@",arrCatid.description);

答案 2 :(得分:1)

我没有测试过,但希望是这样。

NSMutableArray *arrCatID = [NSmutableArray alloc]init];
for (NSDictionary *instance in myDictionary){ // myDictionary is the values of "Value"
         NSString *content = [instance objectForKey:@"catename"];
        for (NSString *catName in stringArray) { // stringArray --> has already the CatNAmes with you 
           if (catName == content) {
             [arrCatID addObject:[instance objectForKey:@"ctgid"];
           break;
          }
       }
  }