Retrieving the present precipitation amount from a Java Script API

I'm having some issues with extracting information from this list because I don't have much experience with JavaScript and APIs. The API I'm working with provides data for the current hour, but I'm struggling to retrieve that specific value. Here's the link to the API:

Can anyone offer some guidance on how to solve this issue?

For more information about the API, you can refer to the documentation here:

Whenever I try to initialize a List and extract the value for "hour n", it always returns 0.

Answer №1

The API can be accessed using the fetch method.

To extract precipitation values from the result, we can utilize the Array.map() function.

A sample precipitation object will have the following structure:

{ time: '2022-12-16T16:00' precipitation: 0.1 }

Subsequently, these objects can be displayed in a table for the entire week by dynamically creating elements using document.createElement.

async function getPrecipitation() {
    const url = 'https://api.open-meteo.com/v1/gfs?latitude=53.08&longitude=8.81&hourly=precipitation';
    let result = await fetch(url).then(resp => resp.json());
    let precipitation = result.hourly.time.map((time, idx) => ({ time, precipitation: result.hourly.precipitation[idx]}));
    return precipitation;
}

function showPrecipationInTable(rows) {
    let el = document.getElementById('output');
    for(let row of rows) {
        let rowEl = document.createElement('tr');
        rowEl.innerHTML = `<td>${row.time}</td><td>${row.precipitation}</td>`;
        el.appendChild(rowEl)
    }
}

async function getAndShowPrecipitation() {
    let precipitation = await getPrecipitation();
    showPrecipationInTable(precipitation);
}

getAndShowPrecipitation()
 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d4f4242595e595f5c6b4c5d6d19031d031d">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

 <table id="output" class="table table-striped">
  <tr>
<th>Time</th>
<th>Precipitation</th>
  </tr>
</table> 

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 causes Node's crypto module to generate varying outputs for identical strings?

I'm currently attempting to execute the following program: var crypto = require('crypto'); var a = crypto.createHash('md5').update('89Zr-J591').digest('hex'); var name = '89Zr−J591'; var b = crypto. ...

Having trouble with the width of the Material-UI drawer feature

Encountering an issue with the material-ui drawer. I adjusted the width of the drawer container, which led to a problem where the drawer remains slightly inside the page and visible without clicking the button. It seems to be related to the transform attri ...

Adding substantial sections of HTML without any adjustments

While I am working on DOM manipulation, I have encountered the need to insert large blocks of HTML. I am looking for a more efficient way to do this rather than relying on concatenation or creating a messy code structure. Consider the simple code snippet b ...

What is the best way to implement a switch case with multiple payload types as parameters?

I am faced with the following scenario: public async handle( handler: WorkflowHandlerOption, payload: <how_to_type_it?>, ): Promise<StepResponseInterface> { switch (handler) { case WorkflowHandlerOption.JOB_APPLICATION_ACT ...

What is the mechanism behind the operation of the square brackets operator?

Currently focused on C programming, however, this question pertains to low-level concepts that transcend specific languages. I am curious about how a program effectively retrieves the correct data using array[0] or array[6], irrespective of the type of da ...

Building a straightforward RESTful API for user authentication with Node.js, MongoDB, and Express.js

Can someone provide guidance on creating a RESTful API using Node.js, Express.js, and MongoDB? Specifically, I am looking for assistance with writing the schema for login and sign up pages, as well as comparing data in MongoDB using Node.js Express.js. As ...

JqueryUI Autocomplete functions flawlessly on JSFiddle but fails to work on the actual website

After spending hours working on it, I still can't seem to figure it out. The code functions perfectly on JSFiddle, but not on my own website. Here is the link to the JSFiddle: http://jsfiddle.net/x69chen/sbAR6/16/ I've also included the links ...

Employing jQuery to extract the text from the h4 class="ng-binding" element beyond the Angular scope

Is it possible to retrieve the current text content of <h4 class="ng-binding"></h4>? The text content is generated dynamically within the angular.js setup. I am interested in finding a way to extract this text using jQuery or JavaScript from ...

The .removeAttr('checked') method fails to function as expected

I am currently using CodeIgniter. Check out this example of my code. Please fill the textbox and check the checkbox next to it, then click on the "add" link. You will notice that it does not work as expected..removeAttr('checked') newDiv.find(&a ...

Cypress - A Guide to Efficiently Waiting for the Outcome of a Javascript Function Import

I am interested in creating a Javascript library to act as a wrapper for 3rd party APIs. I have decided to write the API wrapper as a standalone file rather than using Cypress Custom functions, so that I can share the library with teams who are not using C ...

The use of Bootstrap carousel indicators effectively controls event propagation

One way to achieve the desired effect is by implementing a solution like the one provided in this example from Bootstrap. When interacting with the indicators quickly, the animations can stack on top of each other, resulting in a strange chain of events. ...

React function causing website to freeze upon dispatch

I created a function in the child component to handle checkbox selection and trigger setDispatch(true). Unfortunately, whenever I check the checkbox, the website freezes and stops responding until I close and reopen it. Here is the function: const [ ...

Can the Automator tool capture a specific section of a website in a screenshot?

Is it possible to use automator to navigate through a store's website category and open each product in a new tab? Alternatively, is there a software that can extract all the product URLs from a specific website? For example, this website has 14 prod ...

Fate, the ethereal PhantomJS, and complete isolation from the online world

My goal is to execute Karma tests using PhantomJS on a continuous integration server that lacks internet access. The process begins with running npm install --no-registry followed by grunt. Grunt Karma is set up for single run (singleRun: true) Everything ...

Modify the background color of checkboxes without including any text labels

I am looking to customize my checkbox. The common method I usually see for customization is as follows: input[type=checkbox] { display: none; } .my_label { display: inline-block; cursor: pointer; font-size: 13px; margin-right: 15px; ...

Improving the Sum of Pairs solution on Codewars

Seeking assistance in optimizing a solution for a problem that has already been identified. However, the existing code is not efficient when dealing with large arrays - view the problem on codeWars : Sum of Pairs Below is the current code snippet: var s ...

Executing a method to retrieve a value from an empty function in Node.js

I am currently dealing with the code snippet below: function done(err, file) { //handling of code here return "test"; } function process() { retext() .use(keywords) .process(sentence, done); return val; } The proce ...

Sending a jQuery form to a node.js connect-form involves passing the form data through AJAX to

On the server side, I have implemented the following function as an expressjs middleware: function objCreation(req, res, next){ req.form.complete(function(err, fields, files){ if (err) { next(err); } else { // Set params in request ...

Differences Between Android and JavaScript: Ensuring Library Validity

Validation in JS is provided by the validator library which can be found at https://www.npmjs.com/package/validator Is there an equivalent library for validation in Android? If so, what is the name of Android's library? ...

Develop interactive div elements with the help of JavaScript/jQuery

Exploring dynamic div creation using javascript or jquery and looking for guidance. <div id="clickable"> <button class="start">Default</button> <button class="random">Randon</button> <button class="gradient"> ...