0

I have a JSON array being pulled into XCode with a key and value. I can get the keys. I can get the values. But is there an easy way to combine them into a single array?

The following code works, but I end up with two separate arrays (channels and channelKeys).

This seems like an inelegant way to create a single array which contains both the key and its value.

-(void) convertArray : (NSMutableArray *)data{

    // Set data
    NSMutableDictionary *dic = [data objectAtIndex:0];

    for (NSString *key in [dic allKeys]) {
        [channels addObject:[dic objectForKey:key]];
    }

    // Set Key Array

    NSMutableDictionary *dic3 = [data objectAtIndex:0];
    NSArray *keys = [dic3 allKeys];

    [channelKeys addObjectsFromArray: keys];

}
2
  • Are channels and channelKeys supposed to be the same array? It looks like you are trying to store the array in the form [value1, value2, value3, key1, key2, key3]. Is that your intention? Commented Dec 30, 2014 at 17:03
  • 1
    This seems like a foolish thing to do, vs simply keeping the values in a dictionary. (And, BTW, a "JSON array" does not contain keys and values -- that's a "JSON object".) Commented Jan 2, 2015 at 4:05

1 Answer 1

1

If you are trying to create an array of the form [key1, value1, key2, value2, key3, value3...] then try something like the following (recall that keys are not restricted to NSStrings)

for (id key in [dic allKeys]) {
    [resultArray addObject:key];
    [resultArray addObject:[dic objectForKey:key]];
}
Sign up to request clarification or add additional context in comments.

1 Comment

For reference, you can simply do "for (id key in dic)". Iterating on a dictionary returns the keys by default.

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.