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

77 views Asked by At

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!

2

There are 2 answers

0
Haresh Ghatala On BEST ANSWER

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];
    }
}
0
Yagnesh Dobariya On
NSInteger *total=0;
NSArray *arr=[NSDictionary objectForKey=@"order_item"];
for(NSDictionary *dic in arr){
    NSArray *array=[dic objectForKey=@"special_item"];
    for(NSDictionary *d in array){
        total=total+[[d objectForKey=@"price"] intValue];
    }
}
NSLog("Total:- %d",total);