Amit
Amit

Reputation: 4886

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.

Upvotes: 2

Views: 1370

Answers (2)

Krunal
Krunal

Reputation: 79636

Use compactMap as flatMap is deprecated.

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

enter image description here

Upvotes: 3

pacification
pacification

Reputation: 6018

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"]

Upvotes: 4

Related Questions