How to Transform JSON Element into a JavaScript Array in AngularJS?

Implementing AngularJS to fetch values in JSON format using $resource call. The model element I require is a Javascript array structured as:

[
[1328983200000, 40],
[1328983200000, 33], 
[1328983200000, 25],
[1328983200000, 54],
[1328983200000, 26], 
[1328983200000, 25]
];

This data will be utilized for Flot charts and is present in the following JSON format:

{
"marks1":15,
"marks2":20,
"dailyMarks":{
"2013-02-27T07:25:35.000+0000":40,
"2013-03-01T07:25:35.000+0000":33,
"2013-02-26T07:25:35.000+0000":25,
"2013-02-23T07:25:35.000+0000":54,
"2013-03-03T10:12:59.000+0000":26,
"2013-03-02T07:12:59.000+0000":25},
}

The crucial elements are within "dailyMarks". Although I can convert this to a Javascript array, my current Controller code isn't producing the desired outcome:

function MyController($scope, $resource) {

    var User = $resource('/marks/fetch?from=:from&to=:to', {from: inStartDate, to: inEndDate}, {
        getAll: {method: 'GET', isArray: false}
    });

    $scope.changeDate = function(fromDate, toDate) {
        $scope.marks = User.getAll({from: fromDate, to: toDate});
    };
    var imarks = User.getAll();
    $scope.marks = imarks;

    var list = imarks.dailyMarks, arr = [];

    for (var key in list) {
        arr.push([+new Date(key), list[key]]);
    }

    $scope.myModel = arr;
};

Facing issues with the conversion process resulting in an empty arr[] within the model. Seeking assistance on rectifying this issue.

Answer №1

The issue at hand stems from the asynchronous nature of the $resource service, despite its appearance of being synchronous in its API. To delve deeper into this topic, refer to this detailed explanation:

To resolve this, it is advisable to incorporate your array post-processing within a success callback following a call to the resource. Here is an example:

function MyController($scope, $resource) {

    var User = $resource('/marks/fetch?from=:from&to=:to', {from: inStartDate, to: inEndDate}, {
        getAll: {method: 'GET', isArray: false}
    });


    $scope.marks = User.getAll({from: fromDate, to: toDate}, function(marksFromServer){
      //post processing <-- goes HERE
    }
);
};

Additionally, instead of repeatedly redefining the User resource within a controller, it is recommended to encapsulate it within a factory and inject User into your controller.

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

Place the item at the top of the list before scrolling downwards

I'm struggling with what seems like it should be a simple task. My goal is to add new items to the top of a list and have the list scroll down to show the new item. So far, I've managed to create and add a new list item using this code snippet: ...

I'm trying to retrieve information from openweathermap in order to show it on my app, but I keep running into an error that says "Uncaught RangeError: Maximum

I recently created a div with the id 'temporary' in order to display data retrieved from the openweathermap.org API. However, I am encountering an error in the console and I'm not sure why. This is my first time working with APIs and I would ...

Creating a custom data type with a specific value in GraphQL

I am new to graphQL and have some questions regarding it. After going through the documentation, I decided to build something of my own. Currently, my setup is quite simple. At the beginning of my application, I have the following code: const express = ...

The accumulation of classes occurs during the cloning process of a template used for a data array

Encountered an issue while duplicating a template div to generate elements for a dataset. The problem arises from classes stacking up when creating elements for each data entry. Sample JavaScript code: $(document).ready(function(){ var data = [ { ...

Delayed execution of Ajax request

Currently watching a Youtube video that explains the Call Stack and Event loop when dealing with Async events like Ajax calls. According to the video, JavaScript execution occurs line by line. Let's try running a sample program: var xhttp = new XMLHt ...

Error: Unable to encode data into JSON format encountered while using Firebase serverless functions

I am currently working on deploying an API for my application. However, when using the following code snippet, I encountered an unhandled error stating "Error: Data cannot be encoded in JSON." const functions = require("firebase-functions"); const axios = ...

Button for AngularJS delete request

I have developed a live polling application that allows users to create, view, and delete questions from the table pools stored in the RethinkDB database. The issue lies with the delete functionality. While sending a DELETE request using POSTMAN successfu ...

Automatically submitting Ajax form upon loading the page

I am attempting to use ajax to automatically submit a form to a database upon page load. The form and php code work perfectly when manually submitted, but for some reason, the ajax function does not trigger. Despite checking the console for errors and con ...

Revamp the angular design of the mat-tree UI bottom border line issue

Can you help me with changing the direction of the mat tree from right to left? I need to remove the bottom border, please refer to the image here ...

Why does my chart.js disappear every time I perform a new render?

Hey there, I'm facing an issue with my code. Let me paste what I have... import React, { memo, useEffect } from 'react'; import Chart from "chart.js"; /* redux-hook */ import { useSelector } from 'react-redux' const lineChart = m ...

How to generate JSON from an NSDictionary in iOS

Hello, I am struggling to create a JSON string using NSDictionary and so far I have not been successful. {"user":{"username":"test","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbcfdec8cffbdcd6dad2d795d8d4d6">[em ...

Performing asynchronous operations in React with axios using loops

On the backend, I have a socket set up to handle continuous requests from the server. Now, my goal is to send requests to the backend API continuously until a stop button is clicked. Using a loop for this task is considered bad practice as it never checks ...

What is the process for accessing information from Symantec through their API?

Experiencing a 400 status code error currently. Feeling a bit stuck on what steps to take next. The 400 status code typically relates to syntax issues. How can I properly format my output into JSON file structure? import requests, json, urllib3 urllib3.d ...

Postback fails to trigger following JavaScript onchange event

Within my asp.NET application, I have incorporated a control that validates form input data using server-side logic. The concept is simple - drag the control to the desired location, configure it in the code behind, and watch as the form gets validated. ...

Guide on converting snake_case JSON to dynamic format in PascalCase:

Here is a code snippet that works perfectly: string json = @"{""MyProperty"" : ""bar""}"; var payload = JsonConvert.DeserializeObject<dynamic>(json); string typedProperty = payload.MyProperty; //contains "bar" Now, let's attempt to handle sn ...

The Reactjs dependency tree could not be resolved

In my current project, I've been attempting to integrate react-tinder-card. After running the command: npm install --save react-tinder-card I encountered this error in my console: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency ...

Combining characters with JSON key names in Python

I am working with a JSON file that contains data where the keys in the custom_fields can vary for each id. The challenge is that when importing this data into BigQuery, field names cannot begin with a number. To solve this issue using Python 3.7, I am expl ...

When Highcharts and AngularJS team up, beware of the memory leak!

I've integrated highcharts into my AngularJS application using the highcharts-ng directive, but I'm encountering a persistent memory leak issue. My app is a slideshow with rotating slides that include charts. To investigate further, I created 3 ...

AngularJS, Internet Explorer File Upload is freezing after a minute

Encountering a unique issue that is specific to Internet Explorer. In my file upload interface, the on-change event triggers an Angular Directive which then calls a web api service using the following code: element.on('change', event => { ...

Struggling to remove an image while using the onmouseover event with a button?

I am encountering an issue with hiding an image using the onmouseover event not applied directly to it, but rather to a button element. The desired functionality is for the image to appear when the mouse hovers over and disappear when it moves away. Here&a ...