Sorting and Filtering JSON Data by Value in JavaScript: A Comprehensive Guide

After successfully integrating the Star Wars API to show character names from the "people" object in this JSON array retrieved from , I now need to filter the results based on a specific value which corresponds to . The current code displays all species of people, but I want to display only those belonging to the human species. Here's the existing code snippet:

const url = 'https://swapi.co/api/species/1/?format=json';

function fetchData(url) {
    return fetch(url).then((resp) => resp.json());
}

function constructTableRow(data) {
    const row = document.createElement('tr');
    const {
        name,
        height,
        mass,
        hair_color
    } = data;
    row.appendChild(constructElement('td', name))
    row.appendChild(constructElement('td', height))
    row.appendChild(constructElement('td', mass))
    row.appendChild(constructElement('td', hair_color))
    return row;
}

function constructElement(tagName, text, cssClasses) {
    const el = document.createElement(tagName);
    const content = document.createTextNode(text);
    el.appendChild(content);
    if (cssClasses) {
        el.classList.add(...cssClasses);
    }
    return el;
}

const swTable = document.getElementById('sw-table').getElementsByTagName('tbody')[0];

fetchData('https://swapi.co/api/people/').then((data) => {
    data.results.forEach(result => {
        const row = constructTableRow(result);
        swTable.appendChild(row);
    });
});
<table id=sw-table><tbody></tbody></table>

The JSON data is fetched from

How can I modify the code to only display data for characters belonging to the human species?

Answer №1

Have you considered implementing filter in this scenario?

const onlyHumans = data.filter(person => person.species.indexOf('https://swapi.co/api/species/1/') !== -1);

Answer №2

The data retrieved from the species API contains an array of people. Instead of filtering out specific individuals, iterate through the entire people array.

Please be cautious as this approach may encounter issues with SWAPI's rate limiting.

const url = 'https://swapi.co/api/species/1/?format=json';

function fetchData(url) {
  return fetch(url).then((resp) => resp.json());
}

function createRow(data) {
  const row = document.createElement('tr');
  const { name, height, mass, hair_color } = data;
  row.appendChild(createElement('td', name))
  row.appendChild(createElement('td', height))
  row.appendChild(createElement('td', mass))
  row.appendChild(createElement('td', hair_color))
  return row;
}

function createElement(tagName, text, cssClasses) {
  const el = document.createElement(tagName);
  const content = document.createTextNode(text);
  el.appendChild(content);
  if (cssClasses) {
    el.classList.add(...cssClasses);
  }
  return el;
}

const swTable = document.getElementById('sw-table').getElementsByTagName('tbody')[0];

fetchData(url).then(data =>
  data.people.forEach(personUrl =>
    fetchData(personUrl).then(result => {
      const row = createRow(result);
      swTable.appendChild(row);
    })
  )
);
<table id=sw-table>
  <tbody></tbody>
</table>

Answer №3

If you're aware that the URL https://swapi.co/api/species/1/ corresponds to a human species, you can easily verify its existence in the species array by utilizing the filter method.

const isHuman = guy=>~guy.species.indexOf('https://swapi.co/api/species/1/');

The indexOf function can be employed to ascertain whether an element exists within an array. It returns -1 if the element is not found, hence employing bitwise NOT (~) transforms it into truthy if present or falsey if absent by converting -1 to 0.

You can then filter the results based on this function before iterating over them.

data.results.filter(isHuman).forEach(result => {....});

const url = 'https://swapi.co/api/species/1/?format=json';

function fetchData(url) {
    return fetch(url).then((resp) => resp.json());
}

function constructTableRow(data) {
    const row = document.createElement('tr');
    const {
        name,
        height,
        mass,
        hair_color
    } = data;
    row.appendChild(constructElement('td', name))
    row.appendChild(constructElement('td', height))
    row.appendChild(constructElement('td', mass))
    row.appendChild(constructElement('td', hair_color))
    return row;
}

function constructElement(tagName, text, cssClasses) {
    const el = document.createElement(tagName);
    const content = document.createTextNode(text);
    el.appendChild(content);
    if (cssClasses) {
        el.classList.add(...cssClasses);
    }
    return el;
}

const swTable = document.getElementById('sw-table').getElementsByTagName('tbody')[0];

const isHuman = guy=>~guy.species.indexOf('https://swapi.co/api/species/1/');

fetchData('https://swapi.co/api/people/').then((data) => {
    data.results.filter(isHuman).forEach(result => {
        const row = constructTableRow(result);
        swTable.appendChild(row);
    });
});
<table id=sw-table><tbody></tbody></table>

Answer №4

Here's an additional instance using .filter() and .includes() (instead of checking for a negative index):

fetchData('https://swapi.co/api/people/').then(data => {
    data.results
        .filter(person => person.species.includes("https://swapi.co/api/species/1/"))))
        .forEach(human => swTable.appendChild(constructTableRow(human)))
});

Answer №5

Is this code functioning properly?

    getData('https://swapi.co/api/people/').then((responseData) => {

       responseData.results.forEach(individualResult => {
       const tableRow = createRow(individualResult);
       if(individualResult.species === "https://swapi.co/api/species/1/") {
           speciesTable.appendChild(tableRow);
        }
   });

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

Can you incorporate an eventListener within a for loop? If so, what would be the strategy to execute it successfully?

When it comes to handling and displaying large data, I find For Loops and ForEach Loops to be extremely useful. However, adding an eventListener to a loop can present some challenges. In the code snippet below, you'll see that I'm looping through ...

The repetition of the react nodejs page load occurs when the get method is utilized

I've successfully set up a page and function for loading the customer list. However, I'm facing an issue where adding the get method to my code results in it being called every time information is received from the URL and the page is rendered. i ...

Tips for implementing a distinct texture on child elements through traversal techniques

My current dilemma involves working with an object that I've loaded using THREE.ObjectLoader(). This object consists of various elements, resembling a simple box made up of panels and sticks. My goal is to assign different textures to specific child ...

execute the NPM script in the current directory

Within my package.json file for a node project, I have the following test script that utilizes the ts-node package: "scripts": { "build": "tsc", "test": "ts-node" } Executing this script from the root ...

In C#, transmitting byte[] through email and subsequently recovering it

What is the most efficient process for completing these steps in order? Extract a string from a byte array. Transmit this string through email. Receive the string. Convert the string back into a byte array. ...

Customizing the Class of a jQuery UI ui-autocomplete Combobox Container

Is there a way to customize the ui-autocomplete div by adding a custom class? I have several autocomplete widgets on my webpage, and I need to style their drop-downs differently. Since editing the ui-autocomplete class directly is not an option, I am wor ...

Input various information into a single form multiple times and automatically submit it to a Google spreadsheet

I have some data that needs to be transferred to an array and then sent to a Google Sheet. The data looks like this: -|PO: 2005 | 12121211212121,| Qty: 45| BIN:110| eBay| 11/6/2017-| PO: 2165 | 333333333,| Qty: 54| BIN:20| google| 11/6/2017- First, I use ...

PHP JSON array containing key names with periods

Having trouble parsing JSON response from an API because key names include dots? Check out the example JSON below: JSON: { "unit.count": 40413, "device.count": 4893, "registration.count": 3951 } Here's the code snippet you might be usi ...

Calculate the total sum of a specific property within an array using ES6

My goal is to calculate the total unit value by date and create a new array without duplicate dates. For instance, I want to sum up the values of 2015-12-04 00:01:00. This particular date appears twice in the dataset with values of 5 and 6, resulting in: ...

Simulating a JavaScript constructor using Sinon.JS

I need to write unit tests for the ES6 class below: // service.js const InternalService = require('internal-service'); class Service { constructor(args) { this.internalService = new InternalService(args); } getData(args) { let ...

Is it possible to create a dynamic template in Angular using external sources?

My goal is to dynamically load HTML content using AJAX and then compile it, as it contains Angular directives. I have a specific class that includes methods for utilizing Angular outside the scope of an angular controller or directive: var AngularHelper ...

Controlling the file system on a local level through browser-based JavaScript and Node.js

I am currently working on a project that requires users to interact with the file system directly from their browsers. While I have extensive experience in writing client-side JavaScript code and using Node.js scripts for tasks like web scraping, data anal ...

Navigating through nested objects in JSON when working with D3: a guide

Currently, I am in the process of learning D3 using various tutorials. Here is the code snippet I have been working with: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title ...

Utilizing LoopBack Storage Service: Leveraging upload/download functions within JavaScript code

Is there a straightforward way to upload and download files using the storageService.upload and storageService.download functions in my JavaScript/Loopback code? I'm trying to achieve something like this: app.post("/sendFile", (req, res) => client ...

Using jQuery to iterate through an array and reverse its order

Is there a way to loop through an array and change the CSS background color chronologically rather than randomly? Additionally, is it possible to reverse through the same array when the back button is clicked? http://jsfiddle.net/qK2Dk/ $('#right&a ...

Obtain information from a file containing nested JSON objects in R

I am new to utilizing R for programming and I am currently attempting to parse a file that contains nested JSON objects and convert it into an R dataframe. The file format is structured as follows: { "collect": [{ ... // Data details ...

What is the best way to parse a JSON file and create a dynamic webpage using jQuery with the data from the

As someone who is new to working with Node.js and JSON, I am encountering some issues when trying to extract data from a JSON file. Below is the code that I have written: 'use strict'; const fs = require('fs'); let questsRawData = fs ...

Initiate a jQuery modal dialogue box

As an apprentice with no prior experience working with JavaScript, I encountered a problem with my function that calls a popup. The function works fine on the first button, but fails to work on all subsequent buttons. Since the application keeps adding b ...

"Encountering a new error with the creation of a user using AngularJS and Firebase

Attempting to create a user using Angular. myApp.controller('loginCtrl',['$scope','$firebaseAuth','config',function($scope,$firebaseAuth,config){ console.info('[APP-INFO] ~ loginCtrl Start') var ref = ne ...

Guide to integrating and utilizing a personalized JavaScript file within TypeScript components in an Angular 2 application

I have created a standard Angular 2 App using angular-cli. Now, I am trying to incorporate a custom .js file into it. Here is a simplified version of what the file looks like: 'use strict'; var testingThing = testingThing || {}; testingThing. ...