Retrieving JSON data by parsing through specific keys$values

If I only want to list the objects with a particular key-value (like gender) from the JSON array fetched and rendered by this code, where should that filtering process occur - during the fetch or the render?

const URL = "https://ghibliapi.herokuapp.com/people";

const main = document.getElementById("main");
main.innerHTML = "<p>Loading...";

fetch(URL).then((response) => response.json()).then((people) => main.innerHTML = getListOfGender(people));

const getListOfGender = (people) => {
  const filteredPeople = people.filter(person => person.gender === 'female'); // Adjust 'female' as needed
  const names = filteredPeople.map((person) => `<li>${person.name} - ${person.gender} </li>`).join("\n");

  return `<ul>${names}</ul>`;
};

Answer №1

Using GraphQL would be the optimal solution here, allowing you to retrieve only the necessary data fields based on your specific requirements. Whether you modify the getListOfNames function to output individuals whose gender matches your criteria or pass a filtered array of people after fetching them all, the result remains the same.

Answer №2

To retrieve filtered results, you must set up the API endpoint to accept filters. Alternatively, you can filter the data during rendering.

One way to filter using underscore is by using _.where(response, {gender: 'male'})

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

Combining Data from Header to Body using HTML5 and JavaScript

I am struggling to figure out how to transfer variables declared in the script from the header of my code to the body. Specifically, I want to capture the user input in the script and replace a placeholder in the body. Here is an example of what I am tryin ...

What is the reason for function expressions being hoisted when called within Express JS middleware?

It's common knowledge that function declarations are hoisted, allowing them to be called from anywhere in your script. However, this is not the case for function expressions. For instance: test(); const test = () => { console.log(1+3); } ...

Error: An unidentified SyntaxError occurred with an unexpected token < within an anonymous function displayed on the console

In the process of developing an upload file application. The implementation involves AJAX and PHP. Everything functions smoothly on the localhost, but upon transferring it to the web server, a specific error is encountered: Uncaught SyntaxError: Unexpe ...

Using `window.location.href` will terminate any pending asynchronous calls to the API

Before all async calls to the API are completed, window.location.href is triggered when the code runs. Setting a breakpoint on the location resolves the issue. How can I ensure that all calls are finished before invoking window.location.href? Code: const ...

Tips for troubleshooting Node.js React Express applications

Having a background in traditional programming, I am used to putting breakpoints in code and having the debugger take me directly to the problematic section when executed. However, as I delve into web app development, it seems that debugging is limited to ...

Tips for sending JSON-formatted data from a route to jQuery

Currently, I am facing a challenge with passing a JSON file retrieved from an API to jQuery. The goal is to implement an infinite scroll functionality using jQuery before displaying it in an EJS file. The issue arises when `res.json(data)` is utilized; ins ...

ngOptions compare by actual value

My webserver (node.js) serves a JSON file with a list of languages in the format: { "en" : "English", "fr" : "French" } and a separate JSON settings dictionary like this: { "currentLanguage" : "en" }. The select statement is as follows: <select ng-opti ...

Is there a way for me to discover the top trending photos on Instagram today?

Finding information on the Instagram API can be quite challenging due to poor documentation. Is there a method available to discover the most liked Instagram photos by location, such as identifying the top picture liked by Danish users today? Any insight ...

Error in syntax: missing comma after property identifier in MongoDB shell at line 4, position 5

Having trouble with a syntax error Getting error message "missing after property id@shell:4:5" db.movieDetails.updateOne({ title:"The Martian" } , { $set { poster:"http://howle.jpg" } }) db.movieDetails.updateOne({ title ...

Visit the map only after the promises have been fulfilled

In my current project, I am utilizing the loadash map function for data structuring. The data retrieved consists of a series of IDs that require querying the database and integrating the results into the map before returning. However, the data is delayed i ...

Ways to have a dropdown menu automatically close when opening another dropdown

Having an issue with managing multiple href links on a single page. When one link is clicked, it opens a dropdown, but if another link is clicked without closing the first one, the first dropdown remains open. How can I resolve this? I initially attempted ...

AngularJS doesn't display data in a separate file when using ng-select

I am currently utilizing AngularJS to develop a web application. If you would like to view the complete code, you can access it through this link (sample with b.0001.html). AngularJS example My question is how can I retrieve the value ($scope.confirmed in ...

What is the best way to iterate over an associative array and display the contents as a list?

After successfully setting up my initial array, I have been struggling to loop through each row and display the three columns/elements in a tag. Here is the var_dump of my array: array(27) { [3]=> array(3) { ["id"]=> string(3) "295" ["title"]=gt ...

Learn the technique to easily close multiple dynamically added fields in one go using jQuery

Check out my fiddle at the following link: http://jsfiddle.net/ZUDLH/8/ Here is the code snippet: <table id="table"></table> <input type="button" id="addRowBtn" style="border-style: none; cursor: pointer; ...

Adjust the height of the list when including or excluding floated list items that are not in the final row

Within my ul are li elements with varying widths that wrap around inside a container into multiple rows. When removing an li element from the ul, I want the container's height to adjust dynamically in case a row is eliminated. If the removal happens ...

How to use Javascript to fetch HTML content from an external website

Is it possible to access and retrieve scores from for a specific week using AJAX or JSON technology? Each game on the website seems to have a unique class which could make retrieving score information easier. Any guidance or assistance would be greatly ap ...

Capturing jQuery ajax requests in Angular

Within my Angular application, I am utilizing the integrated $.couch API from CouchDB. My goal is to intercept every ajax request, regardless of whether it originates from Angular's $http service or jQuery's $.ajax (which is utilized by $.couch). ...

avoiding the initiation of a new ajax request while a previous one is still in progress

Attempting to create a function that retrieves data from a server on scroll. The function would look something like this... function onscrollend() { $.ajax({ }); } Feeling a bit perplexed about how to verify if the old .ajax() call is still in pr ...

Tips on utilizing Twitter Boootstrap's form validation tooltip messages

Before anything else, let me clarify that I am not inquiring about creating tooltips from scratch using Bootstrap's javascript guide, which can be found in the documentation. I recently utilized type="email" with version v3.3.1. It automatically vali ...

Encountering an exception while parsing JSON

I'm trying to extract specific fields from a JSON object. Here is an example of the JSON data- { "id": "100000224942080000", "name": "Tech Geeky", "first_name": "Tech", "last_name": "Geeky", "link": "https://www.facebook.com/tech.geeky ...