如何从两个不同的数组中找到共同的对象并打印另一个对象?

Posted

技术标签:

【中文标题】如何从两个不同的数组中找到共同的对象并打印另一个对象?【英文标题】:How to find the common object from two different arrays and print another object? 【发布时间】:2018-02-14 12:34:54 【问题描述】:

我有 2 个数组从 2 个不同的 API 接收

预订数组


            addrLine1 = "Al Thanyah Fifth, Dubai, United Arab Emirates";
            addrLine2 = "  ";
            apntDate = "14 Feb 2018";
            apntDt = "2018-02-14 15:31:30";
            apntTime = "03:31 pm";
            apptLat = "25.071102142334";
            apptLong = "55.142993927002";
            "appt_duration" = "";
            bid = 555;
            bookType = 1;
            cancelAmt = 30;
            "cat_id" = 591da979227951a10f004ad7;
            "cat_name" = "Car Wash";
            cid = 21;
            "coupon_discount" = 0;
            "customer_notes" = "";
            "distance_met" = 120;
            email = "fawasfais@gmail.com";
            expireTime = "";
            fname = Fawas;
            "job_imgs" = 0;
            "job_start_time" = "1970-01-01 00:00:00";
            "job_timer" = "";
            pPic = "https://s3.amazonaws.com/iserve/ProfileImages/20170720110011AM.png";
            "payment_type" = 1;
            phone = 568573570;
            "price_per_min" = 10;
            "pro_notes" = "";
            services = "5923f21c2279518a1661cb09,5923f22d2279513f1861cb09";
            status = 2;
            statusMsg = "Provider Accepted.";
            timer = "";
            "timer_status" = "";
            "visit_amount" = 60;
          

选定的服务数组


        "price_per_unit" = 30;
        "sub_cat_id" = 5923f21c2279518a1661cb09;
        "sub_cat_name" = SUV;
        unit = 1;
    ,
        
        "price_per_unit" = 45;
        "sub_cat_id" = 5923f22d2279513f1861cb09;
        "sub_cat_name" = Sedan;
        unit = 1;
    
 
        "price_per_unit" = 65;
        "sub_cat_id" = 5923f23e2279518a1661cb09;
        "sub_cat_name" = Bus;
        unit = 1;
    ,
        
        "price_per_unit" = 75;
        "sub_cat_id" = 5923f24f2279513f1861cb09;
        "sub_cat_name" = Lorry;
        unit = 1;
    

我想将上述两个数组与第一个数组中的“services”键和第二个数组中的“sub_cat_id”进行比较,最后打印包含车辆的公共服务 id 的 price_per_unit。

示例 - 5923f21c2279518a1661cb09,5923f22d2279513f1861cb09 id 在第一个数组中找到,因此打印第二个数组中两个 id 的 price_per_units - 30、45

有什么建议吗? (如果任何代码 sn-ps 需要回答 cmets 中提到的这个问题,我将使用所需的代码编辑和更新问题。

This is how I get the second array from the server

-(void)getServiceTypes

    NSDictionary *queryParams;
    queryParams = @
                    @"ent_sess_token":flStrForStr([[NSUserDefaults standardUserDefaults] objectForKey:KDAcheckUserSessionToken]),
                    @"ent_dev_id":flStrForStr([[NSUserDefaults standardUserDefaults] objectForKey:kPMDDeviceIdKey]),
                   @"ent_catid":_dictAppointmentDetails[@"cat_id"]
                   ;


    NetworkHandler *handler = [NetworkHandler sharedInstance];
    [handler composeRequestWithMethod:@"getSubCategory"
                              paramas:queryParams
                         onComplition:^(BOOL succeeded, NSDictionary *response) 
                             if (succeeded) 

                                 [self getServiceTypesResponse:response];
                             
                         ];
    NSLog(@"param%@",queryParams);


-(void)getServiceTypesResponse:(NSDictionary *)response

    NSLog(@"GETSERVICETYPES%@",response);

    serviceTypeDict = response[@"data"];
    NSLog(@"SERVICETYPEDIC%@",serviceTypeDict);
    serviceTypeArray = response[@"data"];
    NSLog(@"SERVICETYPEARRAY%@",serviceTypeArray);
    serviceTypeIDArray = [[serviceTypeArray valueForKey:@"sub_cat_id"]copy];
    NSLog(@"SERVICETYPEIDARRAY%@",serviceTypeIDArray);




谢谢

【问题讨论】:

您是否为上述 JSON 数据创建了模型类? 第一个是一个对象,它有一个名为“服务”的数组,对吧? @ibnetariq 第一个数组的对象是“services”,它有两个值等于第二个数组的对象键“sub_cat_id” 你需要检查第一个数组的每个对象和第二个数组的每个对象吗? @ibnetariq 我想将上述两个数组与第一个数组中的“services”键和第二个数组中的“sub_cat_id”进行比较,最后在单元格标签中打印包含车辆的公共服务 ID 的 price_per_unit表格视图 【参考方案1】:

让它在操场上工作:

let booking: [String: Any] = [
    "services": "5923f21c2279518a1661cb09,5923f22d2279513f1861cb09",
    "status":2
]

let selectedServices: [[String: Any]] = [
    [
        "price_per_unit": 30,
        "sub_cat_id": "5923f21c2279518a1661cb09",
        "sub_cat_name": "SUV",
        "unit": 1
    ],
    [
        "price_per_unit": 45,
        "sub_cat_id": "5923f22d2279513f1861cb09",
        "sub_cat_name": "Sedan",
        "unit": 1
    ],
    [
        "price_per_unit": 65,
        "sub_cat_id": "5923f23e2279518a1661cb09",
        "sub_cat_name": "Bus",
        "unit": 1
    ],
    [
        "price_per_unit": 75,
        "sub_cat_id": "5923f24f2279513f1861cb09",
        "sub_cat_name": "Lorry",
        "unit": 1
    ]
]

if let bookingServices = booking["services"] as? String 
    let services: [String] = bookingServices.components(separatedBy: ",")

    let commonServices = selectedServices.filter( services.contains( $0["sub_cat_id"] as? String ?? "" ) )
    print(commonServices)

Objective-C 等效项:

NSDictionary *booking = @
                                @"services": @"5923f21c2279518a1661cb09,5923f22d2279513f1861cb09",
                                @"status": @2
                                ;

NSArray *selectedServices =  @[
             @
              @"price_per_unit": @30,
              @"sub_cat_id": @"5923f21c2279518a1661cb09",
              @"sub_cat_name": @"SUV",
              @"unit": @1
              ,
             @
              @"price_per_unit": @45,
              @"sub_cat_id": @"5923f22d2279513f1861cb09",
              @"sub_cat_name": @"Sedan",
              @"unit": @1
              ,
             @
              @"price_per_unit": @65,
              @"sub_cat_id": @"5923f23e2279518a1661cb09",
              @"sub_cat_name": @"Bus",
              @"unit": @1
              ,
             @
              @"price_per_unit": @75,
              @"sub_cat_id": @"5923f24f2279513f1861cb09",
              @"sub_cat_name": @"Lorry",
              @"unit": @1
              
             ];

NSString *servicesString = [booking valueForKey: @"services"];
NSArray *bookingServices = [servicesString componentsSeparatedByString:@","];

NSMutableArray *commonServices = [[NSMutableArray alloc] init];

for (NSDictionary *selectedService in selectedServices) 
    NSString *sub_cat_id = selectedService[@"sub_cat_id"];

    if([bookingServices containsObject: sub_cat_id]) 
        [commonServices addObject: selectedService];
    


NSLog(@"%@", commonServices);

【讨论】:

抱歉没看到。 检查更新的答案。 这行得通!谢谢 :) 使用谓词方法过滤速度很快,如另一个答案中所述。也尝试使用谓词。【参考方案2】:

我认为你应该使用 NSPredicate,因为这是快速枚举。仅两行代码

我在这里使用你的演示内容。

NSDictionary *maindic = @@"price_per_min" :@"10",
                                   @"services":@"5923f21c2279518a1661cb09,5923f22d2279513f1861cb09",
                                  ;

    NSDictionary *dic1 =@@"price_per_unit" :@"30",
                           @"sub_cat_id":@"5923f21c2279518a1661cb09",
                           ;

    NSDictionary *dic2 =@@"price_per_unit" :@"45",
                           @"sub_cat_id":@"5923f22d2279513f1861cb09",
                           ;
    NSDictionary *dic3 =@@"price_per_unit" :@"65",
                          @"sub_cat_id":@"5923f23e2279518a1661cb09",
                          ;

    NSArray *mainArr=  @[dic1,dic2,dic3];

    NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"sub_cat_id == '5923f21c2279518a1661cb09'"];
    NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"sub_cat_id == '5923f22d2279513f1861cb09'"];
    NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[predicate1, predicate2]];

    NSArray *resultArray = [mainArr filteredArrayUsingPredicate:predicate];

它会在resultArray中返回


    "price_per_unit" = 30;
    "sub_cat_id" = 5923f21c2279518a1661cb09;
,

    "price_per_unit" = 45;
    "sub_cat_id" = 5923f22d2279513f1861cb09;

【讨论】:

这是更好更快的解决方案

以上是关于如何从两个不同的数组中找到共同的对象并打印另一个对象?的主要内容,如果未能解决你的问题,请参考以下文章

如何从另一个数组创建一个对象的两个 valueForKey 元素的 NSArray

如何从对象列表中找到最小值?

从两个不同的类型数组中找出共同值

如何从文本文件创建二维数组并在 c 中打印到新文件

如何从jquery中的给定对象数组中打印用户名[重复]

如何按一个元素分组并在 Javascript 中找到另一个元素的平均值?