Home > Blockchain >  Get an Array of Specific Value from the Json Model in Swift
Get an Array of Specific Value from the Json Model in Swift

Time:01-10

I want an array which contains only the userName from my following Model Class:

struct MyModel: Codable {
    let status: Int?
    let message: String?
    let data: [MyModelClass]?
}

struct MyModelClass: Codable {
    let userID, userName, email, emailCode: String?
    let phone, password: String?
    let image: String?
    let dreamInfo: String?

    enum CodingKeys: String, CodingKey {
        case userID = "user_id"
        case userName = "user_name"
        case email
        case emailCode = "email_code"
        case phone, password, image
        case dreamInfo = "dream_info"
    }
} 

I want an array which has only userNames. How to do it in swift?

My model responses like this:

{
    "status": 1,
    "message": "user found ",
    "data": [
        {
            "user_id": "1",
            "user_name": "ali",
            "email": "[email protected]",
            "email_code": "0",
            "phone": "0",
            "password": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
            "image": "",
            "dream_info": "this is my dream"
        },
        {
            "user_id": "2",
            "user_name": "raza",
            "email": "[email protected]",
            "email_code": "0",
            "phone": "0",
            "password": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
            "image": "",
            "dream_info": "this is my dream"
        },
        {
            "user_id": "3",
            "user_name": "usman",
            "email": "[email protected]",
            "email_code": "0",
            "phone": "0",
            "password": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
            "image": "",
            "dream_info": "this is my dream"
        },
        {
            "user_id": "4",
            "user_name": "haroon",
            "email": "[email protected]",
            "email_code": "0",
            "phone": "0",
            "password": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
            "image": "",
            "dream_info": "this is my dream"
        }
    ]
}

I want only the User Names from this model. This is my desired output:

var myArray = ["ali", "raza", "usman", "haroon"]

If there are 10 values in the model class then I need myArray to have all the 10 user names.

CodePudding user response:

A simple modification of the answer of Kudos

var arr: [MyModelClass] = []
for item in data {
    arr.append(item)
}
debugPrint(arr)

CodePudding user response:

To retrieve filtered Array of certain Name:

var arr: [MyModelClass] = []
for item in data where item.userName == "Kudos" {
    arr.append(item)
}
debugPrint(arr)
  •  Tags:  
  • Related