Stephen
Stephen

Reputation: 3465

Search in Array of Dictionaries by key name

I have an array of dictionary, in which i need to search and return matching Dict

let foo = [
    ["selectedSegment":0, "severity":3, "dataDictKey": "critical"],
    ["selectedSegment":1, "severity":2, "dataDictKey": "major"],
    ["selectedSegment":2, "severity":1, "dataDictKey": "minor"],
]

In foo, how can i find for severity:2 and get matching Dict ?

Upvotes: 5

Views: 3952

Answers (3)

Shashi Verma
Shashi Verma

Reputation: 3820

if you work on swift 3.1 -

 let  resultPredicate : NSPredicate = NSPredicate.init(format: "<your Key> CONTAINS [cd] %@", <value which you want to search>)
 let filteredArray = requstData.arrayForColl?.filter { resultPredicate.evaluate(with: $0) };

Upvotes: 0

vadian
vadian

Reputation: 285069

Use the filter function

let foo = [
  ["selectedSegment":0, "severity":3, "dataDictKey": "critical"],
  ["selectedSegment":1, "severity":2, "dataDictKey": "major"],
  ["selectedSegment":2, "severity":1, "dataDictKey": "minor"],
]

let filteredArray = foo.filter{$0["severity"]! == 2}
print(filteredArray.first ?? "Item not found")

or indexOf

if let filteredArrayIndex = foo.indexOf({$0["severity"]! == 2}) {
  print(foo[filteredArrayIndex])
} else {
  print("Item not found")
}

or NSPredicate

let predicate = NSPredicate(format: "severity == 2")
let filteredArray = (foo as NSArray).filteredArrayUsingPredicate(predicate)
print(filteredArray.first ?? "Item not found")

Swift 3 Update:

  • indexOf( has been renamed to index(where:
  • filteredArrayUsingPredicate(predicate) has been renamed to filtered(using: predicate)

Upvotes: 12

Eendje
Eendje

Reputation: 8883

if let index = foo.flatMap({ $0["severity"] }).indexOf(2) {
    print(foo[index])
}

Another way of doing it.

The first example only works if the user is 100% sure all the dictionaries contains "severity" as a key. To make it more safe:

if let index = foo.indexOf({ ($0["severity"] ?? 0) == 2 }) {
    print(foo[index])
}

Upvotes: 2

Related Questions