Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift filter nested array of objects

Tags:

swift

I have an array of Business objects. Each Business object contains an array of key-value pairs, one element of which can be a nested array of ContentBlocks objects.

var masterArray = [
        Business(busName: "Dave's Cafe", busId: 1, website: "http://www.davescafe.com", latLong: (45.541, -45.609),
            actions: [["title": "About Us", "contentId": "123", "actionType": "content"],
                ["title": "Website", "url": "http://www.davescafe.com", "actionType": "web"]],
            contentBlocks:[
                ContentBlock(busName: "Dave's Cafe", busId: 1, contentId: "123", title: "Testola!", body: "Hello there!")
            ]),
        Business(busName:...
]

I can filter the array to return a specific Businesses matching a unique busId by using something like this:

let rtnArray = masterArray.filter{$0.busId == id}
    if rtnArray.count == 1{
        return rtnArray[0]
    } else {
        return // feedback that no matches were found
    }

Additionally, I'd like to return a specific contentBlock by filtering on the unique contentId (if necessary I can also pass the busId of the Business 'owner'). I'm really struggling to move forward so any pointers in the right direction would be great.

like image 340
James Avatar asked Jun 09 '16 15:06

James


1 Answers

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
like image 140
Alexander Avatar answered Sep 28 '22 07:09

Alexander