arraysswiftnestedswift5

Run a loop inside a nested array in swift


I am trying to get result by using a for loop inside nested response by not getting the required result. I have tried but not getting the desired response. Required result is as below.


[
 [["P-1 Test one","P-1 Test Two","P-1 Test Three"]],
 [["P-2 Test One"","P-2 Test One"],["P-2 A-1 Test one","P-2 A-1 Test two","P-2 A-1 Test three","P-2 A-1 Test four"],["P-2 A-2 Test one","P-2 A-2 Test two","P-2 A-3 Test three","P-2 A-4 Test four"]],
 [["P-3 Test One"],["P-3 A-1 Test one","P-3 A-1 Test Two","P-3 A-1 Test three","P-3 A-1 Test four"]]
 ]

I am using below json response to get the required result.

{
    "page_size": 20,
    "page": 1,
    "count": 209,
    "results": [
        {
            "_score": null,
            "plink_id": "plifnW",
        "customer_name": "Primary member one",
            "packages": [
                {
                    "is_addon": false,
                    "addon_price": 0,
                    "parameter": 1,
                    "name": "P-1 Test one",
                    "id": 54,
                    "package_city_prices": {
                        "package_price": 160,
                        "offer_price": 99
                    },
                    "slug_name": "Test-one-slug"
                },
                {
                    "is_addon": false,
                    "addon_price": 0,
                    "parameter": 1,
                    "name": "P-1 Test Two",
                    "id": 54,
                    "package_city_prices": {
                        "package_price": 160,
                        "offer_price": 99
                    },
                    "slug_name": "Test-Two-slug"
                },
                {
                    "is_addon": false,
                    "addon_price": 0,
                    "parameter": 1,
                    "name": "P-1 Test Three",
                    "id": 54,
                    "package_city_prices": {
                    "package_price": 160,
                    "offer_price": 99
                },
                    "slug_name": "Test-Two-slug"
                }
            ],
            "verification_remark": "Duplicate Booking",
            "additional_members": []
        },
        {
            "_score": null,
            "plink_id": "plifnW",
         "customer_name": "Primary member two",
            "packages": [
                {
                    "is_addon": false,
                    "addon_price": 0,
                    "parameter": 1,
                    "name": "P-2 Test One",
                    "id": 54,
                    "package_city_prices": {
                        "package_price": 160,
                        "offer_price": 99
                    },
                    "slug_name": "Test one slug"
                },
                {
                    "is_addon": false,
                    "addon_price": 0,
                    "parameter": 1,
                    "name": "P-2 Test One",
                    "id": 54,
                    "package_city_prices": {
                    "package_price": 160,
                    "offer_price": 99
                },
                    "slug_name": "Test one slug"
                }
            ],
            "verification_remark": "Duplicate Booking",
            "additional_members": [
                {
                    "plink_id": null,
                    "alloted_time": null,
                    "customer_name": "Additional member one",
                    "packages": [
                        {
                            "is_addon": false,
                            "tat_time": null,
                            "name": "P-2 A-1 Test one",
                            "slug_name": "Test_one_slug"
                        },
                        {
                            "is_addon": false,
                            "tat_time": null,
                            "name": "P-2 A-1 Test two",
                            "slug_name": "Test_Two_slug"
                        },
                        {
                            "is_addon": false,
                            "tat_time": null,
                            "name": "P-2 A-1 Test three",
                            "slug_name": "Test_Three_slug"
                        },
                        {
                            "is_addon": false,
                            "tat_time": null,
                            "name": "P-2 A-1 Test four",
                            "slug_name": "Test_four_slug"
                        }
                    ]
                },
                {
                    "plink_id": null,
                    "alloted_time": null,
                    "customer_name": "Additional member Two",
                    "packages": [
                        {
                            "is_addon": false,
                            "tat_time": null,
                            "name": "P-2 A-2 Test one",
                            "slug_name": "Test_one_slug"
                        },
                    {
                            "is_addon": false,
                            "tat_time": null,
                            "name": "P-2 A-2 Test two",
                            "slug_name": "Test_Two_slug"
                    },
                    {
                            "is_addon": false,
                            "tat_time": null,
                            "name": "P-2 A-3 Test three",
                            "slug_name": "Test_Three_slug"
                    },
                    {
                            "is_addon": false,
                            "tat_time": null,
                            "name": "P-2 A-4 Test four",
                            "slug_name": "Test_four_slug"
                        }
                    ]
                }
                ]
        },
          {
            "_score": null,
            "plink_id": "plifnW",
         "customer_name": "Primary member Three",
            "packages": [
                {
                    "is_addon": false,
                    "addon_price": 0,
                    "parameter": 1,
                    "name": "P-3 Test One",
                    "id": 54,
                    "package_city_prices": {
                        "package_price": 160,
                        "offer_price": 99
                    },
                    "slug_name": "test five slug"
                }
            ],
            "verification_remark": "Duplicate Booking",
            "additional_members": [
                {
                    "plink_id": null,
                    "alloted_time": null,
                    "customer_name": "P-3-A-1 additional member",
                    "packages": [
                        {
                            "is_addon": false,
                            "tat_time": null,
                            "name": "P-3 A-1 Test one",
                            "slug_name": "Test_one_slug"
                        },
                        {
                            "is_addon": false,
                            "tat_time": null,
                            "name": "P-3 A-1 Test Two",
                            "slug_name": "Test_Two_slug"
                        },
                        {
                            "is_addon": false,
                            "tat_time": null,
                            "name": "P-3 A-1 Test three",
                            "slug_name": "Test_Three_slug"
                        },
                        {
                            "is_addon": false,
                            "tat_time": null,
                            "name": "P-3 A-1 Test four",
                            "slug_name": "Test_four_slug"
                        }
                    ]
                }
            ]
        }
    ]
}

Here in this response the parameter "additional_mamber" can be empty or can have multiple member or tests. I have used following code to get the result.

for testResult in self.bookingArray?.results ?? [] {
    var testPackageArrayOne = [[String]]()
    for testPackage in testResult.packages ?? [] {
        testPackageArrayOne.append([testPackage.name ?? ""])
    }
    for member in testResult.additional_members ?? [] {
        var newAdditionArray = [String]()
        for additionalMemberTests in member.packages ?? [] {
            newAdditionArray.append(additionalMemberTests.name ?? "")
        }
        testPackageArrayOne.append(newAdditionArray)
    }
    print("testPackageArrayOne==>>",testPackageArrayOne)
    arrayOfTests.append(testPackageArrayOne)
    print("arrayOfTestArrays==>>",arrayOfTests)
}
// Print the resulting array of arrays
for array in arrayOfTests {
    print("individual array for every member ==>>",array)
}
print("member and additional members array ==>>",self.memberNameArray)
                

But not getting the desired result.


Solution

  • Not sure why would you need a third level on your array but should be pretty straight forward using functional programing (map, flatMap):

    let data = Data("""
    {
        "page_size": 20,
        "page": 1,
        "count": 209,
        "results": [
            {
                "_score": null,
                "plink_id": "plifnW",
                "customer_name": "Primary member one",
                "packages": [
                    {
                        "is_addon": false,
                        "addon_price": 0,
                        "parameter": 1,
                        "name": "P-1 Test one",
                        "id": 54,
                        "package_city_prices": {
                            "package_price": 160,
                            "offer_price": 99
                        },
                        "slug_name": "Test-one-slug"
                    },
                    {
                        "is_addon": false,
                        "addon_price": 0,
                        "parameter": 1,
                        "name": "P-1 Test Two",
                        "id": 54,
                        "package_city_prices": {
                            "package_price": 160,
                            "offer_price": 99
                        },
                        "slug_name": "Test-Two-slug"
                    },
                    {
                        "is_addon": false,
                        "addon_price": 0,
                        "parameter": 1,
                        "name": "P-1 Test Three",
                        "id": 54,
                        "package_city_prices": {
                            "package_price": 160,
                            "offer_price": 99
                        },
                        "slug_name": "Test-Two-slug"
                    }
                ],
                "verification_remark": "Duplicate Booking",
                "additional_members": []
            },
            {
                "_score": null,
                "plink_id": "plifnW",
                "customer_name": "Primary member two",
                "packages": [
                    {
                        "is_addon": false,
                        "addon_price": 0,
                        "parameter": 1,
                        "name": "P-2 Test One",
                        "id": 54,
                        "package_city_prices": {
                            "package_price": 160,
                            "offer_price": 99
                        },
                        "slug_name": "Test one slug"
                    },
                    {
                        "is_addon": false,
                        "addon_price": 0,
                        "parameter": 1,
                        "name": "P-2 Test One",
                        "id": 54,
                        "package_city_prices": {
                            "package_price": 160,
                            "offer_price": 99
                        },
                        "slug_name": "Test one slug"
                    }
                ],
                "verification_remark": "Duplicate Booking",
                "additional_members": [
                    {
                        "plink_id": null,
                        "alloted_time": null,
                        "customer_name": "Additional member one",
                        "packages": [
                            {
                                "is_addon": false,
                                "tat_time": null,
                                "name": "P-2 A-1 Test one",
                                "slug_name": "Test_one_slug"
                            },
                            {
                                "is_addon": false,
                                "tat_time": null,
                                "name": "P-2 A-1 Test two",
                                "slug_name": "Test_Two_slug"
                            },
                            {
                                "is_addon": false,
                                "tat_time": null,
                                "name": "P-2 A-1 Test three",
                                "slug_name": "Test_Three_slug"
                            },
                            {
                                "is_addon": false,
                                "tat_time": null,
                                "name": "P-2 A-1 Test four",
                                "slug_name": "Test_four_slug"
                            }
                        ]
                    },
                    {
                        "plink_id": null,
                        "alloted_time": null,
                        "customer_name": "Additional member Two",
                        "packages": [
                            {
                                "is_addon": false,
                                "tat_time": null,
                                "name": "P-2 A-2 Test one",
                                "slug_name": "Test_one_slug"
                            },
                            {
                                "is_addon": false,
                                "tat_time": null,
                                "name": "P-2 A-2 Test two",
                                "slug_name": "Test_Two_slug"
                            },
                            {
                                "is_addon": false,
                                "tat_time": null,
                                "name": "P-2 A-3 Test three",
                                "slug_name": "Test_Three_slug"
                            },
                            {
                                "is_addon": false,
                                "tat_time": null,
                                "name": "P-2 A-4 Test four",
                                "slug_name": "Test_four_slug"
                            }
                        ]
                    }
                ]
            },
            {
                "_score": null,
                "plink_id": "plifnW",
                "customer_name": "Primary member Three",
                "packages": [
                    {
                        "is_addon": false,
                        "addon_price": 0,
                        "parameter": 1,
                        "name": "P-3 Test One",
                        "id": 54,
                        "package_city_prices": {
                            "package_price": 160,
                            "offer_price": 99
                        },
                        "slug_name": "test five slug"
                    }
                ],
                "verification_remark": "Duplicate Booking",
                "additional_members": [
                    {
                        "plink_id": null,
                        "alloted_time": null,
                        "customer_name": "P-3-A-1 additional member",
                        "packages": [
                            {
                                "is_addon": false,
                                "tat_time": null,
                                "name": "P-3 A-1 Test one",
                                "slug_name": "Test_one_slug"
                            },
                            {
                                "is_addon": false,
                                "tat_time": null,
                                "name": "P-3 A-1 Test Two",
                                "slug_name": "Test_Two_slug"
                            },
                            {
                                "is_addon": false,
                                "tat_time": null,
                                "name": "P-3 A-1 Test three",
                                "slug_name": "Test_Three_slug"
                            },
                            {
                                "is_addon": false,
                                "tat_time": null,
                                "name": "P-3 A-1 Test four",
                                "slug_name": "Test_four_slug"
                            }
                        ]
                    }
                ]
            }
        ]
    }
    """.utf8
    )
    

    // MARK: - Booking
    struct Booking: Codable {
        let pageSize, page, count: Int
        let results: [Result]
    
        enum CodingKeys: String, CodingKey {
            case pageSize = "page_size"
            case page, count, results
        }
    }
    
    // MARK: - Result
    struct Result: Codable {
    //    let score: Int?
        let plinkID, customerName: String
        let packages: [ResultPackage]
        let verificationRemark: String
        let additionalMembers: [AdditionalMember]
    
        enum CodingKeys: String, CodingKey {
    //        case score = "_score"
            case plinkID = "plink_id"
            case customerName = "customer_name"
            case packages
            case verificationRemark = "verification_remark"
            case additionalMembers = "additional_members"
        }
    }
    
    // MARK: - AdditionalMember
    struct AdditionalMember: Codable {
    //    let plinkID: String?
    //    let allotedTime: Date?
        let customerName: String
        let packages: [AdditionalMemberPackage]
    
        enum CodingKeys: String, CodingKey {
    //        case plinkID = "plink_id"
    //        case allotedTime = "alloted_time"
            case customerName = "customer_name"
            case packages
        }
    }
    
    // MARK: - AdditionalMemberPackage
    struct AdditionalMemberPackage: Codable {
        let isAddon: Bool
    //    let tatTime: Date?
        let name, slugName: String
    
        enum CodingKeys: String, CodingKey {
            case isAddon = "is_addon"
    //        case tatTime = "tat_time"
            case name
            case slugName = "slug_name"
        }
    }
    
    // MARK: - ResultPackage
    struct ResultPackage: Codable {
        let isAddon: Bool
        let addonPrice, parameter: Int
        let name: String
        let id: Int
        let packageCityPrices: PackageCityPrices
        let slugName: String
    
        enum CodingKeys: String, CodingKey {
            case isAddon = "is_addon"
            case addonPrice = "addon_price"
            case parameter, name, id
            case packageCityPrices = "package_city_prices"
            case slugName = "slug_name"
        }
    }
    
    // MARK: - PackageCityPrices
    struct PackageCityPrices: Codable {
        let packagePrice, offerPrice: Int
    
        enum CodingKeys: String, CodingKey {
            case packagePrice = "package_price"
            case offerPrice = "offer_price"
        }
    }
    

    let bookingArray = try? JSONDecoder().decode(Booking.self, from: data)
    var results: [[[String]]] = []
    for result in bookingArray?.results ?? [] {
        let packages = result.packages.map(\.name)
        let additionalMembers = result.additionalMembers.flatMap(\.packages).map(\.name)
        if additionalMembers.isEmpty {
            results.append([packages])
        } else {
            results.append([packages, additionalMembers])
        }
    }
    

    for res in results {
        print(res)
    }
    

    Should print:

    [["P-1 Test one", "P-1 Test Two", "P-1 Test Three"]]
    [["P-2 Test One", "P-2 Test One"], ["P-2 A-1 Test one", "P-2 A-1 Test two", "P-2 A-1 Test three", "P-2 A-1 Test four", "P-2 A-2 Test one", "P-2 A-2 Test two", "P-2 A-3 Test three", "P-2 A-4 Test four"]]
    [["P-3 Test One"], ["P-3 A-1 Test one", "P-3 A-1 Test Two", "P-3 A-1 Test three", "P-3 A-1 Test four"]]


    or even simpler

    let results = bookingArray?.results.map { result in 
        let packages = result.packages.map(\.name)
        let additionalMembers = result.additionalMembers.flatMap(\.packages).map(\.name)
        return additionalMembers.isEmpty ? [packages] : [packages, additionalMembers]
    } ?? []