0

My json array is like this:

[
    {
        "result_names": [
            "val"
        ]
    },
    {
        "result_names": [
            "val"
        ]
    },
    {
     "result_names": [
            "count",
            "sum"
        ]
    }
]

My output should just be an array with string val, count and sum at array indices 0, 1 and 2 (order doesn't matter) and duplicates should be removed ("val" is repeated twice). I am able to get rid of the duplicates but I am not quite sure to get the third occurrence of result_names at separate indices. Here's my code so far:

Above json is stored as:

NSDictionary* json;
NSMutableArray *resultList = [json valueForKey:@"result_names"];
NSArray *res = [[NSSet setWithArray: resultList] allObjects];

Now, NSLog(@"%@", res); gives me:

        (
        val
    ),
        (
        count,
        sum
    )
)

Now "res.count" returns 2. I want val, count and sum in different indices. Kindly help.

2 Answers 2

1

Your -valueForKey: call is returning an array of arrays, so +setWithArray: can de-dupe identical arrays but not individual elements. You’ll have to do something like this:

NSArray *resultLists = [json valueForKey:@"result_names"];
NSMutableSet *results = [NSMutableSet set];
for (NSArray *resultList in resultLists) {
    [results addObjectsFromArray:resultList];
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the Key-Value Coding collection operator "@distinctUnionOfArrays":

NSArray *json = @[
                        @{@ "result_names": @[@"val"]},
                        @{@ "result_names": @[@"val"]},
                        @{@ "result_names": @[@"sum", @"count"]},
                        ];

NSArray *res = [json valueForKeyPath:@"@distinctUnionOfArrays.result_names"];
NSLog(@"%@", res);

Output:

(
    val,
    count,
    sum
)

(Note that your top-level JSON object is an array, not a dictionary.)

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.