tara tandel
tara tandel

Reputation: 550

flatten array of dictionaries with duplicate values Swift 3.0

I have an Array of dictionaries like this :

let arrayofDictionaries:[[String:Any]] = [
    ["nationalCode": "1570158037", "bookId": 327, "orderDate": "2017-07-24 14:11:52", "mobileNo": "09873456789", "isFavorite": false, "price": 45000, "bookName": "آموزش عربي انساني نکته ها"],
    ["nationalCode": "1570158037", "bookId": 366, "orderDate": "2017-07-24 14:11:58", "mobileNo": "09873456789", "isFavorite": false, "price": 19000, "bookName": "آبي عربي پيش1و2انساني"],
    ["nationalCode": "1570158037", "bookId": 327, "orderDate": "2017-07-24 14:11:52", "mobileNo": "09873456789", "isFavorite": false, "price": 45000, "bookName": "آموزش عربي انساني نکته ها"],
    ["nationalCode": "1570158037", "bookId": 366, "orderDate": "2017-07-24 14:11:58", "mobileNo": "09873456789", "isFavorite": false, "price": 19000, "bookName": "آبي عربي پيش1و2انساني"],
]

The Dictionary inside the array has fixed keys which values would change. I tried this code:

for item in arrayofDictionaries {
    for (kind, value) in item {
        print(kind)
        dic.updateValue(value!, forKey: kind)
    }    
}

but this would eliminate duplicate kies and just return the last values. the output of the above code would be:

dic = ["nationalCode": "1570158037", "bookId": 366, "orderDate": "2017-07-24 14:11:58", "mobileNo": "09873456789", "isFavorite": false, "price": 19000, "bookName": "آبي عربي پيش1و2انساني"]

what i want is a dictionary like this:

let flattenedArray : [String : Any] = [
    "nationalCode": "1570158037", "bookId": 327, "orderDate": "2017-07-24 14:11:52", "mobileNo": "09873456789", "isFavorite": false, "price": 45000, "bookName": "آموزش عربي انساني نکته ها",
    "nationalCode": "1570158037", "bookId": 366, "orderDate": "2017-07-24 14:11:58", "mobileNo": "09873456789", "isFavorite": false, "price": 19000, "bookName": "آبي عربي پيش1و2انساني",
    "nationalCode": "1570158037", "bookId": 327, "orderDate": "2017-07-24 14:11:52", "mobileNo": "09873456789", "isFavorite": false, "price": 45000, "bookName": "آموزش عربي انساني نکته ها",
    "nationalCode": "1570158037", "bookId": 366, "orderDate": "2017-07-24 14:11:58", "mobileNo": "09873456789", "isFavorite": false, "price": 19000, "bookName": "آبي عربي پيش1و2انساني",
]

any help would be appreciated

Upvotes: 1

Views: 529

Answers (4)

Negar Moshtaghi
Negar Moshtaghi

Reputation: 463

do {
        let data = try JSONSerialization.data(withJSONObject: JsoonFactor, options: .prettyPrinted)
        let jsonString = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
        let jr = (jsonString?.replacingOccurrences(of: "\n", with: "", options: .regularExpression))!
        let jrrr = jr.removingWhitespaces()
        let urlEncodedJson = jrrr.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)

Upvotes: 1

Christian Serrano
Christian Serrano

Reputation: 486

Dictionaries are meant to be used with unique keys, it is probable that the process is not eliminating the duplicate keys but the creation itself, the dictionary class even has a function to create a dictionary defining the rules to decide which value to take as the correct from duplicated entries.

Upvotes: 0

mag_zbc
mag_zbc

Reputation: 6982

From your comments we finally get what are you trying to do - you want to turn your arrayOfDictionaries to a String to post it with a request.

It may vary depending on how exactly you want it to look, but if you want to turn your arrayOfDictionaries to string, you can do something like this

var aString : String = ""
for aBook in arrayOfDictionaries {
    if let nationalCode = aBook["nationalCode"] {
        aString.append("nationalCode : " + nationalCode + ", ")
    }
    if let bookId = aBook["bookId"] {
        aString.append("bookId : " + bookId + ", ")
    }
    // and so on, and so forth
}

Why do it manually, instead of just iterating with (key, value) over the dictionary? Unfortunately, due to the fact that Dictionary is implemented as hash map, there is no guarantee that when iterating your keys will appear in the same order they were when you declared the dictionary (actually, it's almost guaranteed that the order will be different).

But again, it's the matter of format your string needs to have. If the order doesn't matter, just iterate with (key, value)

Upvotes: 1

PGDev
PGDev

Reputation: 24341

Although I too didn't understand what exactly are you trying to achieve, but as you mentioned in the comment, to create a URL string from a dictionary , simply use:

func urlString() -> String
    {
        var string = ""

        for key in self.keys
        {
            if let value = self[key]
            {
                string += "&\(key)=\(value)"
            }
        }
        return string
    }

Upvotes: 0

Related Questions