Attempting to fetch JSON data within a function using the Fetch API, in order to utilize the information in a separate function

Looking to extract information from a URL that contains JSON data for multiple objects, I came up with the following code:

static fetchObj(){
fetch("http://localhost:1337/objects")
.then(callback => { 
return callback.json();
})
.then(data => {
console.log(data);
});
}

This allows me to successfully retrieve and output the necessary information.

Next, I need to utilize this data in another function that searches for specific objects based on their ID:

static fetchObjById(id) {
      MyClass.fetchObj()
      .then(
          for(var i=0; i<data.id.length; i++){
            if(data[i].id == id)
              console.log("found");
            else
              console.log("not found");
          }
   }

However, despite attempting various methods, I have been unable to make it work. Any help or advice would be greatly appreciated!

Answer ā„–1

One method to locate the identification number is shown here.

var id = 4;
function retrieveObjectById(data) {
    console.log(data);
    for(var i = 0; i < data.length; i++){
        if(data[i].id === id) {
            console.log('located');
            break;
        }
    }
}

var myData;
fetch('https://jsonplaceholder.typicode.com/users')
  .then(response => response.json())
  .then(data => myData = data)
  .then(() => retrieveObjectById(myData));

Answer ā„–2

then() requires a function as its argument. By using an arrow function, you can easily access the data from the Promise's result.

I suggest moving away from explicit for loops and exploring declarative programming instead. Similar to then(), utilizing forEach() on an array allows you to work with each element using an arrow function, making your code more readable.

In addition, you can streamline the console.log call by first defining the message to be printed based on a condition (using a ternary operator), and then logging that message just once using console.log.

const fetchObjById = (id) => {
  MyClass.fetchObj()
    .then(data => {
        data.forEach(d => {
          const message = d.id === id
            ? 'found'
            : 'not found';
          console.log(message);
        })
      }
}

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

What is the process of converting an android checkbox selection into a string and then inserting it into a database?

Iā€™m encountering a small issue while trying to incorporate checkboxes into my app development project. Any idea how I can achieve the following?: Converting a selected checkbox into a string and then inserting it into a MySQL database. Below is the c ...

Optimizing the display of multiple list items using Javascript for two separate UL elements on a single webpage

How can I display a maximum of 5 list items in two separate UL elements on the same page and hide the rest? Users should be able to see more items by clicking a dynamic "See more" element created by JavaScript. Below are the UL elements I want to work wit ...

What is the best way to draw a rectangle outline in Vue.js without the need for any additional packages?

I have been attempting to craft a rectangle outline using vueJS, but so far I have not had much success. I am hoping to achieve this using only CSS, but despite my efforts, I have not been able to find a solution. My goal is to create something similar to ...

Even after being removed, the input field in Firefox stubbornly maintains a red border

I have a project in progress that requires users to input data on a modal view and save it. The validation process highlights any errors with the following CSS snippet: .erroreEvidenziato { border: 1px solid red; } Here is the HTML code for the moda ...

What is the best method for dividing strings in javascript?

After invoking a JavaScript function, I received the following results: (1, 00), (2, 10), (3, 01), (4, 11) I am looking to store this data in an array or JSON format like this: [{id:1, number: 00},{id:2, number: 10},{id:3, number: 01},{id:4, number: 11} ...

Utilize PHP to open a JSON string file and then convert it into an array

<?php $postcode=$_POST['script']; $myfile = '{ "1": { "Brand":"MITSUBISHI HEAVY INDUSTRIES, LTD.", "Model_No":"SRK20ZMXA-S / SRC20ZMXA-S", "C.Power_Inp_Rated":0.35, "H.Power_Inp_Rated":0.45, "KWH":1881.95, "Cost":564.585}, "2": { "Br ...

Error in sending data to the server via the specified URL: "Http failure response for http://localhost/post.php: 0 Unknown Error" and POST request to http://localhost/post.php failed with error code

Feeling a bit stuck trying to add data to my database. As a junior with PHP and Angular, I am using PHP via XAMPP and Angular 8. Is it possible to create separate files for the post and get methods in the PHP file? app.component.ts import { Component, O ...

Ensure that input field is validated only upon clicking the save button in Angular framework

Can anyone suggest the most efficient method to validate required fields in an input form using AngularJS? I want to display an error message only after the user clicks the save button (submit). Thank you in advance. ...

Error encountered while using Jquery's .each() method on a DOM element and attempting to

Trying to utilize the each() function on my DOM to dynamically retrieve a field, I encountered an issue with the following code: var new_entry = new Object(); $('div[name="declaration-line-entry"]').each(function () { new_entry.name = $(this ...

Ingest JSON child elements using Logstash, structure them appropriately, and load them into Elasticsearch

I have a JSON file that looks like this: "fruits": { "fruit": [ { "id": 1, "label": "test", "tag": "fine", "start": "4", ...

ReactJS Scripts are throwing an error indicating that the function require is not defined

Just starting out with React and I discovered that we can integrate React by adding the necessary scripts to our main index.html file. I followed all the steps to include the script and even made sure to add Babel since I'm writing my main App in JSX. ...

Using Python to transform API response data into a Power BI table

My Python script is used to connect to an API and receives the following response, which needs to be converted into a multi-level table for importing into PowerBI due to its complex data structure (e.g., "rooms" creating issues): The API response is as sh ...

Having trouble with ng build optimization error in Angular?

While developing a real-time chat application using Angular 13, I encountered an issue when trying to build the app for testing on my Node.js web server: ng build Every time I run this command, I receive an error in the console. Here is a screenshot of ...

Generating a dropdown selection list using data from a JSON file

package com.example.root.myapplication; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.wi ...

Make sure a div is displayed on top of any content currently in fullscreen mode

I recently encountered an issue with my Chrome extension where a menu I inserted into the page would disappear whenever a flash or html5 video player went full screen. Is it possible to have two objects in full screen simultaneously, or is there another so ...

Create a roster of individuals who responded to a particular message

Can a roster be created of individuals who responded to a specific message in Discord? Message ID : '315274607072378891' Channel : '846414975156092979' Reaction : āœ… The following code will run: bot.on("ready", async () = ...

Develop a Modal Form using Bootstrap (HTML)

I followed a tutorial on creating a modal form with Bootstrap, you can find it here: http://www.youtube.com/watch?v=HCEbp07hfLw I replicated the steps shown in the video, but when I try to open the page in my browser, nothing appears. I have added the Bo ...

When creating a database for items, which option is more beneficial: using scriptable objects or storing the data in XML

Hey everyone, I've been toying around with the concept of developing an item database. I'm curious to know which option you think would be more practical and user-friendly. If anyone has a list of pros and cons for either, please share them with ...

Encountering a build time issue while incorporating Redis into Next.js

Incorporating Redis into my Next.js project has been beneficial overall. However, during the build process (next build), an error arises when it attempts to connect to Redis, resulting in the following message: Collecting page data ..[ioredis] Unhandled e ...

Using the GSON Library to parse JSON may result in issues with null checks on Long types

I have a Data class that defines two private Long variables, check and cost. Class Data { private Long check; private Long cost; } The JSON string representing my data only includes the "cost" field: "data": { "cost": 5 } When I try to deser ...