1

This code:

server_response = [{id:1},{id:2},{id:3},{id:4}]

I am getting above response from server now I want only the list of ids in one array like

ids = [1,2,3,4];

I know we can do by for loop but it takes long time if thousand of ids inside the response array.

Is there any better way to achieve above equation?

5
  • if you want to see how to do it using loops: see this link :stackoverflow.com/questions/32414456/… Commented Sep 7, 2015 at 11:15
  • 1
    id result = [array valueForKey:@"id"] Commented Sep 7, 2015 at 11:41
  • @Rog :: awesome ...thank you so much.... Commented Sep 7, 2015 at 11:46
  • No worries I'll post it as an answer for future reference. Commented Sep 7, 2015 at 11:47
  • @Rog :: post as an answer so i will make it right answer Commented Sep 7, 2015 at 11:50

3 Answers 3

2
NSArray *result = [yourArray valueForKey:@"id"]

From the documentation for NSArray instance method valueForKey:

Returns an array containing the results of invoking valueForKey: using key on each of the array's objects

Sign up to request clarification or add additional context in comments.

Comments

2
NSMutableArray *resultArray = [NSMutableArray array];
for (NSDictionary *dict in server_response) {

    [resultArray addObject:[dict objectForKey:@"id"]];
}

Try above code. Hope it will help you. Result array has final values

1 Comment

thank you but can we do without for loop becuase if a thousand of ids inside response array then complier take too much time for execution..
0
NSArray *server_response =  @[@{@"id":@"1"},@{@"id":@"2"},@{@"id":@"3"},@{@"id":@"4"}];  

    NSMutableArray *resultArray = [NSMutableArray array];

    NSString *birdtemp;
    for (NSDictionary *object in server_response) {
        birdtemp = object[@"id"];
        [resultArray addObject:birdtemp];
    }
    NSLog(@"%@",resultArray);

OutPut: [ 1, 2, 3, 4 ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.