Search code examples
iosios7nsmutablearraynspredicatensmutabledictionary

ADDITION of values of the specific key from NSMutableDictonary (Using NSPredicate)


I have following JSON response which has been stored in NSMutableDictonary. I want to addition of all the price of special_item.

{
    "order_id": "1",
    "order_name": "xyz",
    "order_item": [
        {
            "item_id": "1",
            "item_name": "myone",
            "special_item": [
                {
                    "s_item_id": "1",
                    "price": "10"
                },
                {
                    "s_item_id": "2",
                    "price": "100"
                }
            ]
        },
        {
            "item_id": "2",
            "item_name": "mytwo",
            "special_item": [
                {
                    "s_item_id": "11",
                    "price": "15"
                },
                {
                    "s_item_id": "22",
                    "price": "110"
                }
            ]
        }
    ]
}

Is it possible to do addition of all the price using NSPredicate ? or How can I get array of all the price values using NSPredicate?(e.g : [@10,@100,@15,@110])

Thank you!


Solution

  • It is so simple

    you can try below code

    NSArray *arr = [dix valueForKeyPath:@"order_item.special_item.price"];
    long total = 0;
    for (id price in arr) {
        if ([price isKindOfClass:[NSArray class]]) {
            total += [[price valueForKeyPath:@"@sum.self"] longValue];
        }
        else {
            total += [price longValue];
        }
    }