Trouble obtaining dates and values in JSON while analyzing Commodity Data Charts

 {
  "data": {
    "success": true,
    "timeseries": true,
    "start_date": "2022-02-01",
    "end_date": "2022-03-02",
    "base": "RUB",
    "rates": {
      "2022-02-01": {
        "USD": 0.012922641020611143
      },
      "2022-02-02": {
        "USD": 0.013024953827785636
      },
      "2022-02-03": {
        "USD": 0.013111232627449121
      },
      "2022-02-04": {
        "USD": 0.013080360583812869
      }
    }
  }
}

This JSON data is the response from an axios query. I have been attempting to extract both the date and USD value for chart plotting using a loop and forEach method, but I am encountering difficulties in obtaining them simultaneously. Check out my current progress with the chart code below.

function fnChart04() {
    var chartArray = [];
    var yesterday = moment().subtract(24, 'hours').format('YYYY-MM-DD');
    var url = "https://commodities-api.com/api/timeseries?access_key=XYZed&start_date=2022-02-01&end_date="+yesterday+"&base=RUB&symbols=USD";
    var header = { headers: {'Accept': 'application/json; odata=nometadata'} };
    axios.get(url, header).then(function (response) {
        var results = response.data;

        let rate = results.data.rates.USD;
        let date = results.data.rates[0];

        // Struggling here - unable to effectively loop through rates to separate date and USD value for insertion into chartArray.

        chartArray.push({x: date, y: rate});

        new Chart(document.getElementById("myChart04"), {
            type: 'line',
            data: {
                labels: chartArray.map(function(a) { return a.x; }),
                datasets: [{ 
                    data: chartArray,
                    label: "RUB | USD",
                    borderColor: "#f93154",
                    backgroundColor: "#fee3e8",
                    fill: true
                }]
            },
            options: {
                response: true,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
                
            });
    });
        
}

If you have any pointers or advice on how I can achieve this task more efficiently, I would greatly appreciate it. It seems like there's a simple solution that I'm overlooking.

Answer №1

To iterate through the keys within the rates object, you can utilize the Object.keys method and then populate the chartArray

let info = {
  "data": {
    "success": true,
    "timeseries": true,
    "start_date": "2022-02-01",
    "end_date": "2022-03-02",
    "base": "RUB",
    "rates": {
      "2022-02-01": {
        "USD": 0.012922641020611143
      },
      "2022-02-02": {
        "USD": 0.013024953827785636
      },
      "2022-02-03": {
        "USD": 0.013111232627449121
      },
      "2022-02-04": {
        "USD": 0.013080360583812869
      }
    }
  }
}

let chartArray = [];
Object.keys(info.data.rates).forEach((key) => chartArray.push({x: key,y: info.data.rates[key]["USD"]}))

console.log(chartArray)

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

Is there a way to integrate jQuery validation on an ajax form that queries the database for a specific value in Ruby on Rails?

Recently, I added a phone/sim checker to my system. Users need to input their phone number in the first form field. If the phone number is in the database, a message about finding the phone number will be displayed. If not, the form switches to inputting t ...

Typedi's constructor injection does not produce any defined output

I am utilizing typedi in a Node (express) project and I have encountered an issue related to injection within my service class. It seems that property injection works fine, but constructor injection does not. Here is an example where property injection wo ...

How can I connect an IDE to my Rails project for better development?

I am interested in incorporating an online terminal or IDE into my Rails application. Is there a method to seamlessly integrate existing IDEs with Rails, or develop a new one specifically for this purpose? I have scoured Google but could not find any rele ...

An Angular directive utilizing dual aliases

Is there a simple method to give a directive two distinct names? For example: app.directive(['directiveNameOne', 'directiveNameTwo'], function() {...}); I have created a directive that handles both radio buttons and checkboxes in th ...

What is the best way to change a JavaScript variable into a PHP variable?

I am interested in converting my JavaScript variable to a PHP variable... Currently, I have the following scenario - in the code below there is a variable e, but I would like to utilize e in PHP as $e: <script> function test() { var e = documen ...

Keep the HTML structure of an element in the DOM while excluding it from an ng-repeat loop

I am currently working with the array badge = [{'name':'abc', 'flag': true}, {'name':'cde', 'flag': false}, {'name':'def', 'flag': true} ] After using it with ng-rep ...

Establish a predetermined selection for a drop-down menu

How can I set a default value for a dynamically filled dropdown menu featuring all 12 months in KnockoutJS? I want the default value to be the current month. This is how I am populating the dropdown with information: self.setMonthData = (data ...

PHP Login Script that features Ajax loading of the Header directly on the page itself

I am encountering a challenge with my PHP login script and AJAX implementation. The PHP script successfully redirects the user to a page upon successful login, but when using the AJAX request, the header location loads inside the $('.logresult') ...

Alert in JavaScript if the sentence does not function properly

I need to validate the input value to ensure it only contains "o" or "x". If the input value is anything else, I want to display an alert. Currently, the alert pops up even when I enter "o" or "x". Any assistance would be greatly appreciated. Here is the c ...

What methods can I use to locate the circular dependency within my program?

I am facing numerous circular dependency errors in my Angular project, causing it to malfunction. Is there a way to identify the section of the code where these circular dependencies exist? Warning: Circular dependency detected: src\app&bs ...

Finding the value within a specified range of two numbers in Vue.js

When my code generates a result of 0, I need to determine the corresponding value based on the basic_salary. For example, if the basic_salary is 40,000, it should return the value of "ee": 400. <table class="table table-hover table-borde ...

"Transforming portfolio photos from black & white to vibrant color with the click of a filter button

I'm currently working on creating a portfolio that includes button filters to toggle between black and white images and colored images based on the category selected. While I have successfully implemented the functionality to change the images to bla ...

Updating elements within an array on the fly

In this scenario, let's consider two arrays: array A = [2, 5, 6] and array B = [1, 2, 3, 4, 5, 6, 7, 8]. The values of array B are initially hidden within boxes and become revealed when clicked. The goal is to replace certain values in array B with un ...

Improperly styled select options - Fix it with JQuery

My issue is that my second select dropdown is showing each letter of the data retrieved from the server instead of displaying each item individually. Below is the JQuery code I am using: var selected_table = $("#id_TableName option:selected").text(); ...

Breaking down an array in JavaScript using a variable as the index position

As far as I know, JavaScript arrays can be deconstructed based on a specific index by using the following method. const { 3: selectedByIndex } = arr; This code snippet assigns the value of the element at index 3 to the variable selectedByIndex. But is th ...

Discover the route of a string within an object or array

Given a specific object or array structure, I am looking to verify the existence of a certain path within it. Example 1: const path = "data/message"; const info = { data: { school: 'yaba', age: 'tolu', message: 'true ...

Having trouble getting webpack and babel to start using npm

Greetings, wonderful people of the internet! I am a newcomer to the enchanting world of programming and I am facing a perplexing issue. Although Webpack is trying to guide me towards the solution, I seem to be struggling with fixing it on my own. const pa ...

Ensuring that a service is completely initialized before Angular injects it into the system

When Angular starts, my service fetches documents and stores them in a Map<string, Document>. I use the HttpClient to retrieve these documents. Is there a way to postpone the creation of the service until all the documents have been fetched? In ot ...

ASP.NET jQuery error: Unidentified Web Method

This is my first experience attempting to invoke an ASP.NET page method using jQuery. I encountered a status 500 error indicating that the web method could not be located in the responseText. Below is the jQuery $.ajax call snippet I used: function invoke ...

Creating a Configuration File for POST Requests in NodeJS Express

In my NodeJS application using Express, I currently have a hardcoded method for handling URL POST Request Calls and responding with JSON Files. This means that every time I need to add more POST Request Inputs or specify which JSON File to use, I have to m ...