简体   繁体   English

iOS:如何根据参数值从另一个数组中过滤数组

[英]iOS: how to filter array from another array based on parameter value

I have an NSArray (DataArray) whose response is as follows:我有一个NSArray (DataArray),其响应如下:

  {
"id": "17",
"item_name": "Chivito",
"item_price": "88.00",
"item_status": "Y",
"is_admin": "0",
"item_quantity": "120",
"status": 0
},
  {
"id": "14",
"item_name": "Doughnut",
"item_price": "50.00",
"item_status": "Y",
"is_admin": "0",
"item_quantity": "100",
"status": 1
},
  {
"id": "37",
"item_name": "Drink test ",
"item_price": "80.00",
"item_status": "Y",
"is_admin": "0",
"item_quantity": "12",
"status": 1
},

I have to create another filtered array of only those object whose status value is "1" Please help me how to do it我必须创建另一个过滤数组,其中仅包含状态值为“1”的那些对象请帮我如何做

try this out试试这个

array.filter{(object) -> Bool in 
  if let object = object as NSDictionary {
    if let status = object["status"] as? Int {
      return status == 1
    }
  }
  return false
}

Referring to @Hady ans, In Objective-C you can do it as.参考@Hady ans,在Objective-C 中你可以这样做。 Forgive if there are any formatting/syntax issues.如果有任何格式/语法问题,请原谅。 I am away from my system.我远离我的系统。

NSMutableArry *filteredArray = [NSMutableArray alloc]init];

for (i=0;i<dataArray.count;i++)
{
   if([dataArray[i][@"status"] isEqualToNumber:[NSNumber numberWithInt: 1]])      //if(dataArray[i]["status"] == 1)
    {
      [filteredArray addObject:dataArray[i]];
     }
 }

Hope it helps.. Happy Coding!!希望它有帮助..快乐编码!!

Try predicate its easy and less looping .尝试谓词它的简单和更少的循环。

NSPredicate *sizePredicate = [NSPredicate predicateWithFormat:@"status == %@",[NSNumber numberWithBool: YES]]; NSPredicate *sizePredicate = [NSPredicate predicateWithFormat:@"status == %@",[NSNumber numberWithBool: YES]];

NSMutableArray * filteredSizeArray = [self.arrayFilter filteredArrayUsingPredicate:sizePredicate].copy; NSMutableArray *filteredSizeArray = [self.arrayFilterfilteredArrayUsingPredicate:sizePredicate].copy;

Try:尝试:

OBJECTIVE-C:目标-C:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.status == %d",1];
    NSArray *filtered = [DataArray filteredArrayUsingPredicate:predicate];
    NSLog(@"RESULT: %@", filtered);

You can try this:你可以试试这个:

NSPredicate *prediate = [NSPredicate predicateWithFormat:@"status == %d",1];
arrResult = [myArray filteredArrayUsingPredicate:prediate];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM