简体   繁体   中英

How to get 'key' from 'value' in dictionary which is inside an array?

Here is dictionary which in inside an array,

array With Dict : (
        {
        id = 1;
        name = Arjun;
    },
        {
        id = 2;
        name = Karan;
    },
        {
        id = 3;
        name = Ajit;
    },
        {
        id = 4;
        name = Prashant;
    },
        {
        id = 5;
        name = Sushant;
    }
)

When I will select any 'value', I want to fetch the 'key' associated with that value.

for example :

Suppose I selected 'Prashant' and I want its 'id' ie 4.

How to get 'key' from 'value'?

NSString *myName = @"Prashant";
for (NSDictionary *dict in array) {
    if ([dict[@"name"] isEqualToString:myName]) {
        NSLog(@"%@", dict[@"id"]);
        break;
    }
}

You can loop thru the Array and find the matching entry - value you are looking for. Then get its key.

for (NSDictionary*dic in array)
{  
   NSString * name  = dic[@"name"];

   if([name isEqual:currentSelectedName])
   {
       NSString * id = dic[@"id"];

       NSLog(@"id is : %@",id);

  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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