Heena
Heena

Reputation: 2358

how can I filter NSMutableArray as example?

I am having an NSMutableArray as my original array and I want to filter it out with its keyvalue pair but only certain keyvalue pair as shown in example.

I don't want to use looping logic. Is there any other way to get the required output? I don't want to modify my original array.

original array{
                "name" = "name";
                "end_date" = "test end date";
                "id" = 104;
                "start_date" = "test start date";
                "user_id" = 5;
              },
              {
                 "name" = "name1";
                "end_date" = "test1 end date";
                "id" = 105;
                "start_date" = "test1 start date";
                "user_id" = 5;
            }


want filtered array as
{
        "name" = "name";
        "end_date" = "test end date";
        "start_date" = "test start date";

}
}
         "name" = "name";
        "end_date" = "test end date";
        "start_date" = "test start date";
}

How Can I achieve this without using for loop?

Upvotes: 0

Views: 834

Answers (2)

Joshua Smith
Joshua Smith

Reputation: 6621

You can use enumerateObjectsUsingBlock using something like this (I didn't enumerate all the keys from the NSDictionary:

    NSMutablArray *myNewArray = [NSMutableArray array];
   [myArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
            NSDictionary *myNewDict = [NSDictionary dictionaryWithObjectsAndKeys:[obj valueForKey:@"name"],@"name"]];
            [myNewArray addObject:myNewDict];
   }];

If you wanted just a subset of the elements, you could use an NSPredicate.

Upvotes: 2

Tommy
Tommy

Reputation: 100622

Are the dictionaries mutable? And are you looking to modify the original array in place or create a new array?

The easiest solution if your setup allows it would be:

[array enumerateObjectsUsingBlock:
         ^(id obj, NSUinteger idx, BOOL *stop)
         {
              [obj removeObjectsForKeys:
                  [NSArray arrayWithObjects:
                       @"id", @"userid", nil]
              ];
         }
];

Though a for loop solution would look almost identical.

From a KVC point of view you could use valueForKey: to extract separate arrays of each field you want to keep with no explicit loop, but I can't think of a quick way to integrate those three arrays cleanly into one array of three-entry dictionaries.

Upvotes: 0

Related Questions