Search code examples
iosjsonswiftswift4

How can I filter data comparing two JSON's and to save the result in an array


I need to extract all Posts Titles from an JSON API using another JSON API of users and after that to extract the count of comments for each Post. Here I have:

  1. API for USERS: http://jsonplaceholder.typicode.com/users
  2. API for POSTS: http://jsonplaceholder.typicode.com/posts
  3. API for COMMENTS: http://jsonplaceholder.typicode.com/comments

In Users I have a unique ID, in Posts I have UserID and in comments I have PostID.

For the moment I extracted all data from all three API's in three arrays. Now I need to create two functions:

  • getPostsTitleForSelectedUser()
  • getNumberOfCommentsForEachPost()

Here is a part of code:

    class UserDetailsController: UIViewController {
    
    @IBOutlet weak var detailsTableView: UITableView!
    

    var usersArray = [User]()
    var postsArray = [Post]()
    var commentsArray = [Comment]()
    

    
    func getPostsTitleForSelectedUser() -> String{
        
        let postTitle: String? = "POST TITLE FOR TEST"
        return postTitle!
    }
    
    func getNumberOfCommentsForEachPost() -> String{
        
        let comments = "4131231231"
        return comments
    }


}

Solution

  • Try something like this

    func getPostsTitleForSelectedUser(user: User) -> [String] {
        return postsArray.filter { (post) -> Bool in
            post.userId == user.id
            }.map { (post) -> String in
                return post.title
        }
    }
    
    func getNumberOfCommentsForEachPost(post: Post) -> Int {
        return commentsArray.filter { (comment) -> Bool in
            comment.postId == post.id
        }.count
    }