When transferring data from Django rest framework to a JavaScript array, there may be issues with missing

Struggling to retrieve data from my API endpoint using AJAX. During the iteration of the JSON object to populate my JavaScript array, I seem to be overlooking some values. Here's a breakdown:

API data:

    HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "sales_rev_quota": [],
    "sales_revi": [
        {
            "month": 1,
            "sum": 123000
        },
        {
            "month": 2,
            "sum": 132000
        }
    ],

Below is my code snippet for extracting data into a JavaScript array:

    endpoint = 'api/chart/data'
$.ajax({
  type: "GET",
  url: endpoint,    
  success: function(data){
    window.revi_sum = []
    window.revi_month = []


    window.sales_revi = data.sales_revi
    for(i=0 ; i < sales_revi.length  ; i++){
        revi_sum.push(sales_revi[i].sum)
        revi_month.push(moment().month(sales_revi[i].month - 1).format("MMMM"))
    console.log(revi_month)
    console.log(revi_sum)
    }
},
error: function(error_data){
console.log('error')
console.log(error_data)
}
})

Check out the console output:

    ["January"]
0: "January"
length: 1
__proto__: Array(0)
(index):112 
[123000]
0: 123000
length: 1
__proto__: Array(0)

Answer №1

To resolve the issue, you should move your logs outside of the for loop body.

window.sales_revi = data.sales_revi;
let revi_sum = [];
let revi_month = [];

for (let i = 0; i < sales_revi.length; i++) {
  revi_sum.push(sales_revi[i].sum);
  revi_month.push(moment().month(sales_revi[i].month - 1).format('MMMM'));
}

console.log(revi_month);
console.log(revi_sum);    

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

Control the outcome of ajax response

I have implemented an ajax post method to retrieve data from the backend. $.ajax({ type: "POST", url: URL_one, data: submitData }).then(function (response) { console.log("Ajax response", response); }); Upon inspecting th ...

Guide on integrating web api on android with javascript, jquery, and jsonp

I am attempting to create a button in my Android application that, when clicked, retrieves information from a web API and displays the results on my screen. Here is the code that performs the necessary tasks, but I need to integrate it into my Android pag ...

Guide to retrieving environment variables within React/Node.js applications running in Kubernetes pods

While setting environment variables in Kubernetes pods, I encountered an issue when trying to access them in either Node.js or React front-end code using process.env.TEST (where TEST is present in the environment as secrets), as it always returned undefine ...

Navigating with Nokia Here maps: plotting a path using GPS coordinates

I am currently developing a GPS tracking system and my goal is to visually represent the device's locations as a route. The challenge I'm facing is that there is a REST API available for this purpose, but my client-side application relies on soc ...

Guide to running examples of three.js on a local web browser

Currently, I am attempting to run the examples from three.js locally in a web browser on MacOS. To do this, I have cloned the entire three.js repository and attempted to open a file in a browser (such as three.js/examples/misc_controls_orbit.html). However ...

Issue 415 encountered when attempting to transmit JSON data to Spring MVC using AJAX

I am encountering an issue while trying to send a JSON object to Spring MVC. Despite my AJAX function gathering input field data from a form and attempting to send the JSON to the controller, I keep receiving a 415 error code. <script type="text/javas ...

What is preventing me from creating accurate drawings on canvas?

I'm currently working on a paint application and facing an issue. When I place the painting board on the left side of the screen, everything works fine and I can draw without any problems. However, when I move it to the right side of the screen, the m ...

Sharing Global Variables in Node.js: What's the Best Way to Pass Them into Required Files?

Recently, I decided to organize my gulpfile.js by splitting it into multiple files within a /gulp folder. However, I encountered an issue when trying to pass a variable debug (boolean) into these files to control the behavior of the gulp command being incl ...

What is the best way to locate the key with the greatest value in an array that is less than or equal to a certain

In my data structure, I have an array that maps user levels to the minimum points required for each level. Here's how it looks: $userLevels = array(0 => 0, 1 => 400, 2 => 800); The keys represent user levels and the values represent the min ...

Enhancing Bootstrap Date Picker with Custom Buttons: A Tutorial

I am attempting to enhance the datepicker functionality by including a custom button, similar to the today button. My goal is to insert a button at the bottom of the calendar each month. This button will be named "End of the month" and will display the c ...

In Vue.js, when attempting to arrange an array of objects in descending order based on a specific key (such as "name"), the intention is to prioritize data containing uppercase letters to be displayed

I am struggling to organize an array of objects based on a specific key (name). My goal is to have the data with uppercase letters appear first, but for some reason, it's displaying the lowercase data first. I've been using the lodash method "ord ...

Adjust the size of the font in accordance with the value of the span text

I am looking to adjust the font size based on the value within the span element. The numbers in the class name may vary. Issue: using text() retrieves all values (e.g. 50020) I want to incorporate each() and $this in some way. How can I do this? Thank ...

Encountering Internal Server Error when running Node-Express app on render.com with query parameters live

Currently, I am facing an issue while attempting to execute a live route with query using my nodejs express application on render.com. Strangely, all other routes connected to the crud operations are functioning properly except for the search filter route ...

I am having trouble setting an object in the state using React hooks

When assigning an initial value to a state as null, the setState method does not hold the value when assigned. Calling an API in useState returns an object which cannot be directly put into setState. const [userProfile, setProfile] = useState(null); cons ...

"Using JavaScript to Make Requests on Mobile Devices via HTTP

Greetings everyone, I have a query regarding implementing an endpoint api in my mobile application. For instance, suppose I have a server handling data and I want to notify my mobile application about new updates by sending a post request. Is this feasibl ...

How does the useEffect React hook perform its comparison process?

One of my favorite JavaScript expressions is: []==[] // false Let's now explore what the React documentation says about skipping side effects: React allows you to skip applying an effect if certain values have not changed between re-renders. To a ...

Find values in a SQL query grid

I am working with a grid that is linked to a cfc, displaying an id column and a checkbox column (boolean). Upon loading, I need to retrieve a list of ID values only for those records where the checkbox is checked. <script language="JavaScript"> fun ...

In the realm of Node.js and Express, an error has been thrown: "Router.use() cannot function without a middleware component, yet received a + gettype(fn)."

While developing an application with Node.js, I encountered the following error: throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) ^ TypeError: Router.use() requires a middleware function but got a ...

Is it necessary to have the script tag as the first tag in the body of the HTML?

I have a script file that needs to be included by third party implementors on their web pages. It is crucial for this script to be the first tag within the body element, like so: <body> <script type="text/javascript" src="/my_script.js"></ ...

The filtering and sorting features of Ng-table do not seem to be working properly when dealing with grouped data

Currently, I am in the process of learning angular.js and have recently started using the ng-table directive. While I have successfully managed to group my data and display it using ng-table, I seem to be facing issues with sorting and filtering the data. ...