Home How to filter a NSArray by Key:value, that is in a NSDictionary
Reply: 0

How to filter a NSArray by Key:value, that is in a NSDictionary

user2517
1#
user2517 Published in June 21, 2018, 4:41 am

Im trying to figure out how to filter out the Dictionary of NSArrays by the value "name"

// Is an Array of a dictionary, by key : values

var teamFilteredList = [[String:Any]]()
var teamList = [[String:Any]]() 

Fetch:

    let string = "https://api/connect/"
    let url = NSURL(string: string)
    let request = NSMutableURLRequest(url: url! as URL)
    request.httpMethod = "GET"
    let session = URLSession.shared
    let tache = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
        if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray {
            print(jsonObj)
            teamList = jsonObj as! [[String : Any]]

            DispatchQueue.main.async {
                self.teamCollectionView.reloadData()
            }
        }
    }
    tache.resume()

This code is the result and gets put in teamList

JSON:

({
    id = 1;
    logo = "testLogo";
    name = "testTeam1";
    "url" = "https://example.com";
},
    {
    id = 2;
    logo = "testLogo";
    name = "testTeam2";
    "url" = "https://example.com";
},
    {
    id = 3;
    logo = "testLogo";
    name = "testTeam3";
    "url" = "https://example.com";
})

Example of what it looks like once put in teamList:

let example = [[id: "1", logo: "image", name: "testTeam1", url: "https"], [id: "2", logo: "image", name: "testTeam2", url: "https"]] 

Code Trying to Filter:

 let array2Name = teamFilteredList.flatMap { $0["name"] }
    teamFilteredList = teamList.reduce(teamFilteredList, { result, value in
        !array2Name.contains(where: { $0 as! _OptionalNilComparisonType == value["testTeam3"] }) ? result + [value]: result
    })

So far this code has been horrible. But there's nothing else online that tells me how to do it cut dry. So I've been stuck.

leads to crash:

Could not cast value of type '__NSCFString'

Update:

I have a collection view that is populated from a fetch by a NSURL that gives me a Dictionary filled with NSArrays and i want to filter out all the NSArray indexes in that dictionary by a value that is already in the NSArray Indexes by the key: "name"

This answered Question in this link final answer, but its not up to date and yields errors. here

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.404147 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO