添加来自 NSMutableDictonary 的特定键的值(使用 NSPredicate)
ADDITION of values of the specific key from NSMutableDictonary (Using NSPredicate)
我有以下 JSON 响应已存储在 NSMutableDictonary
中。我想加上 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"
}
]
}
]
}
是否可以使用 NSPredicate
添加所有 price?或者如何使用 NSPredicate
获取所有 price 值的数组?(例如:[@10,@100,@15,@110])
谢谢!
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);
就是这么简单
你可以试试下面的代码
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];
}
}
我有以下 JSON 响应已存储在 NSMutableDictonary
中。我想加上 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"
}
]
}
]
}
是否可以使用 NSPredicate
添加所有 price?或者如何使用 NSPredicate
获取所有 price 值的数组?(例如:[@10,@100,@15,@110])
谢谢!
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);
就是这么简单
你可以试试下面的代码
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];
}
}