2

I have an array with 4 Dictionaries with key @"preference" like as follows

 (
        {
          preference = Nose;
        },

        {
          preference = "Heart rate";
        },

        {
          preference = Glucose;
        },

        {
          preference = Food;
        }
)

Now i want to retrieve an array for these dictionary values like"

 (
    Nose, Heart rate,  Glucose,  Food
 )

How s'd i get it.. Thanks in advance

0

4 Answers 4

24

A one-liner:

NSArray *resultingArray = [arrayOfDictionaries valueForKeyPath:@"preference"];
Sign up to request clarification or add additional context in comments.

1 Comment

You might get marginally better performance in this case by using -valueForKey:
9

Try it:

NSArray *result = [dictionaryObject valueForKeyPath:@"preference"];

It'll solve your Problem

Comments

2

Do something like this:

NSMutableArray *collectedValues = [NSMutableArray arrayWithCapacity:array.count];

for (NSDictionary *dict in array) {
    NSString *value = [dict objectForKey:@"preference"];
    if (value) {
        [collectedValues addObject:value];
    }
}

Comments

2

Try with this code:
myArray is your first array mySecondArray is the array you have in the end

 NSMutableArray *mySecondArray = [[NSMutableArray alloc] init];

        for (int i = 0; i < [myArray count] ; i++)
        {
            NSDictionary *tempDict = [myArray objectForIndex:i];
            [mySecondArray addObject:[tempDict objectForKey@"preference"]];


        }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.