Swift filter nested array of objects

Here's a solution to what I think you're asking:

 var contentBlocks = masterArray
                         .flatMap{$0.contentBlocks}
                         .flatMap{$0}
                         .filter{$0.contentId == "123"}

Outputs a [ContentBlock] containing all ContentBlock objects that match the filter from within all Business objects.

  1. The first flatMap makes the list of Businesses into an [ContentBlock?]
  2. The flatMap flattens the [ContentBlock?] into a [ContentBlock]
  3. The [ContentBlock] is filtered

When you are dealing with model and want to search the nested custom object of class.

Here is class example.

public final class Model1  {
// MARK: Properties

public var firstname: String?
public var lastname: String?
public var email: String?
public var availabilities: [Availability]?
public var username: String?
}

public final class Availability {
var date: String
var day : String

init(date: String, day: String) {
    self.date = date
    self.day = day

    }
}
public final class AvailData {
var am: String?
var pm: String?

init(am: String?,pm: String?) {
    self.am = am
    self.pm = pm
   }
}

let make an array of Model1.

var arrData = [Model1]()

In my case, I want to search in availabilities array. So I put below logic and it work perfectly.

 let searchData = arrData.filter({ singleObj -> Bool in
     let result = singleObj.availabilities?.filter({ $0.date == "2019/09/17" })
     return result?.count > 0 ? true : false
 })

This swift code will return only those records which match 2019/09/17

Tags:

Swift