Home > Enterprise >  How to trim dictionary for both empty and null values
How to trim dictionary for both empty and null values

Time:01-14

How to remove dictionary for empty or null value From API response data some times it get values or empty "" or null.

    struct StudentField {

        var studentID: String?
        var studentName: String?
        var subjectName: String?
        init(_ json: JSON) {
            studentID = json["student_id"].stringValue
            studentName = json["name_id"].stringValue
            subjectName = json["subject_Name"].stringValue

          let studentDict =   [
            "Id": studentID,
            "name": studentName,
            "subject": subjectName
           ]

            let cleanDictionary = studentDict.reduce(into: [String: Any]()) { $0[$1.key] = $1.value }

         var dict = [String:Any]()
            for element in cleanDictionary {
                print(element)
}

How to Trip dictionary for Empty "" null value ?

input ["student_id": "" "name_id": "", "subject_Name" : "Maths"]
OutPut ["subject_Name" : "Maths"]

CodePudding user response:

You can filter dictionary by using filter method:

var model2 = ["student_id": "" ,"name_id": "", "subject_Name" : "Maths"]
var filteredEmpty = model2.filter( { !$0.value.isEmpty })
print(filteredEmpty)

Output is :

["subject_Name": "Maths"]

Or you can use compactMapValues like :

model2 = model2.compactMapValues { val -> String? in
if val != "" {
    return val
}
return nil
}
print(model2)

Output is :

["subject_Name": "Maths"]

CodePudding user response:

I would say the best approach as Leo Dabus mentions is to use the Codable protocol and you can implement your own init method to ignore nil values and add any other logic that you desire.

Have a look at some great answers on that here and in my opinion this is the best way to do this, it will save you a lot of boilerplate code when it comes to parsing and cleaning up.

However, with that being said, to answer your question, one way I would use to get your desired output is to use filter.

Here is a quick look at the Apple documentation on how to use it.

Here is an example:

let input = ["student_id": "", "name_id": nil, "subject_Name": "Maths"]

// Add your desired logic, I am checking for nil and empty strings
let output = input.filter { $0.value != nil && $0.value != "" }


print(output)

The output here should give you ["subject_Name": Optional("Maths")]

  •  Tags:  
  • Related