I would like to know the best way to compare two JSON data sets, filter out any matching data, and then store the remaining results

To efficiently extract all Post Titles from a JSON API, I am utilizing another JSON API of users to further retrieve the count of comments for each Post. Here are the APIs being used:

  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

The Users API provides a unique ID, while the Posts API includes UserID, and the Comments API contains PostID.

After extracting data from all 3 APIs into separate arrays, the next step is to create two functions:

  • getPostsTitleForSelectedUser()
  • getNumberOfCommentsForEachPost()

A snippet of the code implementation is shown below:

    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
    }


}

Answer №1

Here is a possible solution you can try:

func retrieveTitlesForUser(posts: [Post], user: User) -> [String] {
    return posts.filter { (post) -> Bool in
        post.userId == user.id
        }.map { (post) -> String in
            return post.title
    }
}

func countCommentsForPost(comments: [Comment], post: Post) -> Int {
    return comments.filter { (comment) -> Bool in
        comment.postId == post.id
    }.count
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Traversing JSON Data using Vanilla JavaScript to dynamically fill a specified amount of articles in an HTML page

Here is the code along with my explanation and questions: I'm utilizing myjson.com to create 12 'results'. These results represent 12 clients, each with different sets of data. For instance, Client 1: First Name - James, Address - 1234 Ma ...

Develop a CSS layout for the specified design

Aiming to achieve a unique layout using dynamic html strings. The challenge arises when transitioning to the second page as the layout does not adjust upward and images cannot be added to the first page. Attempting to implement the following sample code ...

Modifying the color of a variety of distinct data points

There was a previous inquiry regarding Changing Colour of Specific Data, which can be found here: Changing colour of specific data Building upon that question, I now have a new query. After successfully changing the 2017 dates to pink, I am seeking a way ...

Does anyone know of a CSS/JavaScript framework that can be used to replicate the look and functionality of the iOS home

I'm wondering if there is a CSS/JavaScript framework that replicates the layout of an iOS home screen. I want to create a kiosk website with a grid layout similar to Android/iOS where apps can be displayed as icons. ...

How can I update my outdated manifest v2 code to manifest v3 for my Google Chrome Extension?

Currently, I am developing an extension and using a template from a previous YouTube video that is based on manifest v2. However, I am implementing manifest v3 in my extension. Can anyone guide me on how to update this specific piece of code? "backgro ...

Why is the toggle list not functioning properly following the JSON data load?

I attempted to create a color system management, but as a beginner, I find it quite challenging! My issue is: When I load my HTML page, everything works fine. However, when I click on the "li" element to load JSON, all my toggle elements stop working!!! ...

Incorporating CSS animations into Vue.js while an API call is being made

When a specific icon is clicked, an API call is triggered: <i class="fas fa-sync" @click.prevent="updateCart(item.id, item.amount)"></i> I am looking to add an animation to rotate the icon until the API call is complete or ...

Is there a way to open an HTML file within the current Chrome app window?

Welcome, My goal is to create a Chrome App that serves as a replacement for the Chrome Dev Editor. Here is my current progress: background.js chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('backstage.html', { ...

The issue of the color CSS rule not being applied to the button element when transitioning from disabled to enabled on browsers like Safari 14+ is a common challenge

There seems to be an issue with frontend form validation code affecting the disabled attribute of a submit button within a form. Two different css rules are applied for the enabled and disabled states, including changes in the text color of the button ele ...

Retrieve jQuery CSS styles from a JSON database

I've been attempting to pass CSS attributes into a jQuery method using data stored in a JSON database. However, it doesn't seem to be functioning as expected. I suspect that directly inputting the path to the JSON variable may not be the correct ...

What is the process of using an if statement in jQuery to verify the existence of a property in a JSON file?

I am working on a task to incorporate an if statement that checks for the existence of a specific property in a JSON file. If the property exists, I need to display its value within HTML tags <div class='titleHolder'> and "<div class=&ap ...

Safari on iOS 11.4 ignoring the 'touch-action: manipulation' property

I ran into an issue while developing a React web app that I want to work seamlessly across different platforms. My goal was to allow users to interact with a div element by double-clicking on desktop and double-tapping on mobile devices. However, when tes ...

What is the process for developing multiple screens or views in PhoneGap?

Currently working on a reading app and decided to give phoneGap a shot for the first time. I'm pretty proficient in HTML, CSS, and JS, but not very familiar with xCode. In this app, I plan to have a button on the home screen that redirects users to an ...

Issues with iOS 7's absolute positioning not functioning properly within a table-responsive container

I successfully implemented fixing the first two left columns in my tables by following the instructions on . The columns are only fixed when the screen size is less than 768px, making the table scrollable (check it out on jsFiddle). This functionality work ...

"Maximizing battery life: Efficient video playback on iOS in low power

Summary: I am currently working on a website that features a video set as the background which autoplays. However, I have encountered an issue on iOS devices when "Low Power Mode" is activated - the video fails to play and instead displays a large "Play" i ...

Utilizing Javascript to Extract Data from Twitter Json Files

Can someone provide assistance with parsing JSON feed text retrieved from Twitter? I am looking to access and apply style tags to elements like the link, created date, and other information. Any tips on how I can achieve this task successfully would be g ...

Is it acceptable to replicate another individual's WordPress theme and website design in order to create my own WordPress website that looks identical to theirs?

It may sound shady, but a friend of mine boasts about the security of his WordPress website, claiming it's impossible to copy someone else's layout or theme. However, my limited experience in web development tells me otherwise. I believe it is po ...

SharePoint 2013 on a mobile device does not support scrolling within iframes

Recently, I set up a SharePoint 2013 website with a few iframes. However, when I access the site on my mobile devices (iPad and Android), I am unable to scroll through the entire page by touching within the iframe. I attempted to solve this issue by inclu ...

Is it normal that my website isn't scrollable on an iPhone?

I have a hunch that the issue is related to the CSS, or perhaps it could be due to including the parallax JavaScript library. You can view the site at Below is the SASS code snippet: @import "compass/css3"; /* Sticky footer styles ---------------------- ...

Transfer the layout from one HTML file to multiple others without the need to retype the code

I am working on developing an e-commerce website with HTML/CSS. My goal is to have a consistent template for all product pages that are accessed when clicking on a product. However, I do not want to manually code each page using HTML and CSS. Is there a mo ...