Search code examples
iosswiftnsarraynsdictionary

Getting data from array of dictionaries in an array


I have created an Array of Dictionaries:

let tempArray = [["id":"1","Name":"ABC"],["id":"2","Name":"qwe"],["id":"3","Name":"rty"],["id":"4","Name":"uio"]]

Now I have to create an array of Name only.

What I have done is this:

var nameArray = [String]()
for dataDict in tempArray {
    nameArray.append(dataDict["Name"]!)
}

But is there any other efficient way of doing this.


Solution

  • You can use flatMap (not map) for this, because flatMap can filter out nil values (case when dict doesn't have value for key "Name"), i.e. the names array will be defined as [String] instead of [String?]:

    let tempArray = [["id":"1","Name":"ABC"],["id":"2","Name":"qwe"],["id":"3","Name":"rty"],["id":"4","Name":"uio"]]
    let names = tempArray.flatMap({ $0["Name"] })
    print(names) // ["ABC", "qwe", "rty", "uio"]