Retrieve the properties of an object

I have a JavaScript program where I retrieve values from a JSON file and store them in an array. However, when I attempt to access the elements of this array, it returns nothing.

Below is the function that pushes temperatures:

temperatures = []
get_info = (data) => {
    var data = JSON.parse(data)
    for(var i = 0; i < data['list'].length; i++){
        temperatures.push(String(data['list'][i]['main']['temp']))
    }
}

Here is how I fetch the data and call the function:

weather = (city_name) => {
var key = '.......';
var base_url = 'http://api.openweathermap.org/data/2.5/forecast?';
var url = base_url + 'appid=' + key + '&q=' + city_name + '&units=metric';
fetch(url)
    .then(response => response.text())
    .then(contents => get_info(contents))    
}

When logging temperatures, it shows an empty array [].

How can I correctly access the elements of the temperatures array?

Answer №1

It appears that your code is working perfectly fine. Just remember that the fetch operation is asynchronous, meaning that the data in the temperatures variable will only be accessible once the promise is resolved.

To verify if the temperatures variable contains the correct values, you can log it to the console after invoking the get_info method:

weather = (city_name) => {
    var key = '.......';
    var base_url = 'http://api.openweathermap.org/data/2.5/forecast?';
    var url = base_url + 'appid=' + key + '&q=' + city_name + '&units=metric';
    fetch(url)
        .then(response => response.text())
        .then(contents => {
            get_info(contents);

            console.log(temperatures); // --> Data available here!
        });    
};

On a related note, if you are aware that the API returns JSON data, you could simply use the json method of the response instead of converting the text response to JSON using JSON.parse:

temperatures = [];
get_info = (data) => {
    for(var i = 0; i < data['list'].length; i++){
        temperatures.push(String(data['list'][i]['main']['temp']))
    }
};

weather = (city_name) => {
    var key = '.......';
    var base_url = 'http://api.openweathermap.org/data/2.5/forecast?';
    var url = base_url + 'appid=' + key + '&q=' + city_name + '&units=metric';
    fetch(url)
        .then(response => response.json())
        .then(contents => {
            get_info(contents);

            console.log(temperatures); // --> Data available here!
        });    
};

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

Ways to dynamically update CSS properties (such as changing the color scheme throughout the entire application)

I have a question... If you're interested in conditional styling, the best approach is to utilize either ng-class or ng-style. However... For instance, let's say I'm an admin and I would like to customize the color of my application using ...

Saving $routeParam in a variable within a factory service in AngularJS Store

Recently I started working with Angular and now I'm attempting to extract the project ID from the URL and use it as a variable within a service. Here's my current code snippet: app.config( ['$routeProvider', function($routeProvi ...

Using a single function to generate multiple instances of a table in JavaScript

My journey to learning javascript led me to create a simple game called circle of crosses. Below is the code I used: (JS) // JavaScript code here (HTML) <!DOCTYPE html> <html> // HTML code here </html> I came across an issue whil ...

The icon is not being displayed when the onHover event on the Material UI component is triggered

I am currently working on adding a delete icon to a Material UI MenuItem component. I've created a state field within the component's state called isHovering, which is initially set to false. The goal is to display the delete icon when hovering o ...

Achieving the Menu Hover Effect - step by step guide to recreating this stylish effect

I recently came across a stunning hover effect on the main menu of a website (red rectangles above menu). It's quite impressive! I found it here: Now, I want to incorporate this same effect into my own website. Unfortunately, there doesn't seem ...

modify the structure of an object according to specific conditions

So, I have this object that looks like the following. I'm currently working on restructuring the object based on the parent and child relationship. var b = []; for(var i=0;i<a.length;i++){ if(a[i].parent == null){ const children = a.filter(x => ...

Utilizing Regex to Authenticate a CAGE Code

Our task is to create a RegEx pattern that can accurately validate a CAGE Code A CAGE Code consists of five (5) positions. The code must adhere to the following format: The first and fifth positions must be numeric. The second, third, and fourth position ...

The iconbar feature in the mobile menu is experiencing functionality issues

I am currently experimenting with the iconbar property of mmenu (here: ) Unfortunately, I am encountering an issue. The menu opens as expected when I run the code. However, upon closing the menu, it first closes completely and then the container slides sl ...

The AngularJS array data is not displaying correctly

I am having trouble displaying comments array data in HTML properly. The data appears the same as it is in the comments array. What could be causing this issue? How should I proceed? <ul class="media-list" ng-controller="dishDetailController as menuCt ...

Assistance required: Click on the button to select and copy all text within the specified paragraph ID

Hey there! I've got a div with a dropdown menu that reveals text and images based on the selected option. What I want to achieve is having a button that allows users to copy all the content inside the div. Below is my sample code for the div dropdown ...

What is the process for adding to a highly nested array in mongoose?

Here is the Model I am working with: const MessagesSchema = mongoose.Schema({ //for individual message text: { type: String, required: true } }, { timestamps : true }) const MessagesCollectionSch ...

Removing all items with a specific ID and its related items in Javascript: How to achieve this recursively?

I am currently facing some challenges in figuring out the most effective approach for this scenario. For example, consider the data structure below: const arr = [{ parentId: 1, children: [ { childId: 11 }, { childId: 21 }, { childId: 31 }, ...

Is there a way for me to record the variable's name instead of its linked data?

Currently, I am developing a node.js program that monitors the prices of different currencies. While I can successfully retrieve the prices, I would like the program to also display the names of the currencies along with their prices. In the code snippet b ...

Creating formGroups dynamically for each object in an array and then updating the values with the object data

What I am aiming to accomplish: My goal is to dynamically generate a new formGroup for each recipe received from the backend (stored in this.selectedRecipe.ingredients) and then update the value of each formControl within the newly created formGroup with t ...

Node.js and JavaScript promises are not pausing for the sequelize query to complete

The promise mentioned below should ideally return the customer and blox slot as part of the booking record in the second .then(). However, it seems that addCustomer and addBooking have not been executed yet. When I added await to addBooking or addCustomer ...

When using the HTML5 input type time in Chrome and the value is set to 00:00:00, it may not be fully completed

After inputting the html code below <input id="time_in" type="time" step="1" name="duration"> and setting the value in the browser to "00:00:00", everything appears fine. However, upon inspecting the console or submitting the form, the value gets ...

Positioning of dropdown in Material UI select component

Unfortunately, I am encountering an issue with the Menuprops attribute and cannot seem to adjust the position of the drop-down box. Despite following the instructions from other similar queries, the desired outcome remains unachieved. My goal is to have t ...

Tips for building a versatile fetch function that can be reused for various JSON formats within a React application

Using the fetch method in various components: fetch(url) .then(result => { if (!result.ok) { throw new Error("HTTP error " + result.status) } return result.json() }) .then(result => { ...

Playing back an Audio object using JavaScript

I'm facing an issue with replaying an audio sound every time the game starts in my Cocos2d javascript code. The sound plays correctly the first time, but subsequent attempts to play it result in no sound being heard. Below is my code snippet: var my ...

Colorbox scalePhotos function malfunctioning

The scalePhotos option in Colorbox does not seem to be working correctly for me. I have tried various methods to set it, including initializing Colorbox using the following code snippet right before the closing </body> tag in my HTML: jQuery('a ...