Generate a four-dimensional array populated with the data retrieved from an Ajax request

In my JavaScript code, I have an array that looks like this:

var data = [
          { y: '2017-01', a: 50,  b: 90, c:110},
          { y: '2017-02', a: 65,  b: 75, c:120},
          { y: '2017-03', a: 50,  b: 50, c:10},
          { y: '2017-04', a: 75,  b: 60, c:170},
          { y: '2017-05', a: 80,  b: 65, c:60},
          { y: '2017-06', a: 90,  b: 70, c:30},
          { y: '2017-07', a: 100, b: 75, c:10},
          { y: '2017-08', a: 115, b: 75, c:0},
          { y: '2017-09', a: 120, b: 85, c:0}
        ]

I've set up an ajax call to retrieve JSON data.

$.ajax({
                type: "POST",
                url: "php/get_incomes_months.php",
                data: {year:current_year},
                dataType: "json",
                success: function(data) {  
                    var data_array = [
                        {y:data[0]['date'], a:data[0]['validated'], b:data[0]['revenue'], c:data[0]['costes']},
                        {y:data[1]['date'], a:data[1]['validated'], b:data[1]['revenue'], c:data[1]['costes']}
                    ];
                    fooDone(data_array); //after we have data, we pass it to fooDone    
                },
                error: function(data){

                }
            });

The JSON response is structured as follows:

0   Object
validated   "0"
revenue "50244.81"
costes  "0"
date    "2017-01"
1   Object
validated   "44788.16"
revenue "30640.51"
costes  "0"
date    "2017-02"
2   Object
validated   "68324.64"
revenue "80363.51"
costes  "11072.73"
date    "2017-03"
3   Object
validated   "0"
revenue "50244.81"
costes  "0"
date    "2017-04"
4   Object
validated   "2738"
revenue "103145.62"
costes  "11"
date    "2017-05"
5   Object
validated   "510"
revenue "1459283.09"
costes  "213"
date    "2017-06"
6   Object
validated   "24034.21"
revenue "50367.81"
costes  "0"
date    "2017-07"
7   Object
validated   "24"
revenue "50244.81"
costes  "0"
date    "2017-08"

As you can see in the success function, I am currently manually creating the array objects. Any suggestions on how I can improve this process with a FOR loop?

success: function(data) {  
                        var data_array = [
                            {y:data[0]['date'], a:data[0]['validated'], b:data[0]['revenue'], c:data[0]['costes']},
                            {y:data[1]['date'], a:data[1]['validated'], b:data[1]['revenue'], c:data[1]['costes']}
                        ];

Your assistance would be greatly appreciated.

Answer №1

Your current code always returns an array with two elements, which may not produce the desired outcome.

To achieve the desired results, it is recommended to initialize an empty array and push the custom object to it in each iteration.

success: function(data) {
  var data_array = [];
  data.forEach(function(obj) {
    data_array.push({
      y: obj['date'],
      a: obj['validated'],
      b: obj['revenue'],
      c: obj['costes']
    });
  });
  fooDone(data_array);
},

Alternatively, you can use the .map() method to create your custom array from the original data array. Here's how you can modify your code:

success: function(data) {
  var data_array = data.map(function(obj) {
    return {
      y: obj['date'],
      a: obj['validated'],
      b: obj['revenue'],
      c: obj['costes']
    };
  });
  fooDone(data_array);
},

This approach will generate a custom object for each object in your data array, containing the specified properties.

Answer №2

Implement Array.prototype.map to generate a fresh array based on the values of the original data array.

var data = [
  { date: '2017-01', validated: 50,  revenue: 90, costes:110},
  { date: '2017-02', validated: 65,  revenue: 75, costes:120},
  { date: '2017-03', validated: 50,  revenue: 50, costes:10},
  { date: '2017-04', validated: 75,  revenue: 60, costes:170},
  { date: '2017-05', validated: 80,  revenue: 65, costes:60},
  { date: '2017-06', validated: 90,  revenue: 70, costes:30},
  { date: '2017-07', validated: 100, revenue: 75, costes:10},
  { date: '2017-08', validated: 115, revenue: 75, costes:0},
  { date: '2017-09', validated: 120, revenue: 85, costes:0}
];
var updated_data = data.map(e => ({y: e.date, a: e.validated, b: e.revenue, c: e.costes}));
console.log(updated_data);

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

The Vue component does not render the JS Promise and instead displays it as

After setting up a promise that will be returned once a correct event is called with the correct action, I have the following code: import {EventBus} from "./EventBus"; export function completed() { EventBus.$on('queue-action', e => { ...

The jQuery AJAX call is successful in Firefox, but unfortunately, it is not working in Internet Explorer

I've encountered a perplexing issue with an AJAX call. It's functioning perfectly fine in Firefox, but for some reason, it's not working in IE. Curiously, when I include an alert() specifically for IE, I can see the returned content, but the ...

What is the best way to send a function along with personalized data?

Currently, I am working on a project using node.js with socket.io. I am looking for a way to have socket.on() use a unique callback function for each client that joins the server. Here is my current technique: I have created a simple JavaScript class whi ...

Once I've located the correct document, how can I search for the object with the specific date and then modify it in mongoose?

I am currently working on creating a heatmap using react-d3-heatmap, and the data structure required for this is [{date: Date, count: Number}]. Below is the schema I have set up for this model. const HeatMapSchema = new mongoose.Schema({ user: {type: ...

Learn how to design a customized loading screen using CSS with Phonegap

Currently working in Android with Phonegap / Cordova, I am faced with the challenge of optimizing page loading time due to numerous DOM objects being created. To address this issue, I am attempting to implement a "Loading..." screen to prevent users from b ...

Manipulating JSON data fetched through AJAX beyond the success callback

I'm facing an issue with storing JSON data received via AJAX in an external variable for future use. I came across this answer on Stack Overflow (load json into variable), which provided some basic insights, but it seems like I might be missing someth ...

What steps are involved in setting up a connection between wit.ai and a server through PHP

For my latest project, I've been working on developing a Facebook bot using Chatfuel. One of the key functions I set up is sending all user responses to my server using a Json API. This allows me to pass data from the user's message to interact w ...

React form input values fail to refresh upon submission

After attempting to upload the form using React, I noticed that the states are not updating properly. They seem to update momentarily before reverting back to their original values. I am unsure of why this is happening. Take a look at this gif demonstrati ...

The function of disabling a form is not affected by the use of jquery $.post

$('#com_form').submit(function(){ var ele = $(this); $.post("includes/agenda_com.php", { text : ele.find('textarea').val(), id : ele.find('#agenda_id').val(); }, fun ...

What is the best way to retrieve the current complete URL in a Next.js/Typescript component?

I'm working on a component and I need to retrieve the current full URL. Here's a simplified version of what I have: /** * Share dropdown component */ export const ShareDropdown: React.FC<{ className: string }> = ({ className, }) => { ...

Limiting the ability to pan to a single globe within the Google Maps API

I need help with restricting panning on a Google Maps API map to just one globe. By default, the map allows continuous panning east/west, causing it to repeat endlessly. I found a solution by henningj in response to this question var allowedBounds = new g ...

What steps should be taken for the authentication process when using Active Directory (with LDAP) with an AngularJS/JavaScript frontend?

Currently, I am tackling a project that involves authenticating users in an application using their Windows credentials. The frontend is built with AngularJS and the backend with Java. After conducting extensive research, I came to the realization that it ...

In what way does s% access the title attribute within the Helmet component?

I am seeking clarification on how the reference to %s is connected to the title attribute of the <SEO /> component within the <Helmet /> component in the gatsby starter theme. Can you explain this? Link to GitHub repo On Line 19 of the code: ...

All responses in Rails API will be rendered using camelCase format for consistency

I'm working on configuring my Rails API to return all JSON responses in camelCase. Currently, I am utilizing Netflix Fast JSON API for serialization and handling errors in the following way: render json: { errors: command.errors }, status: :unauthori ...

[Vue alert]: "Maximum" property or method is not declared in the instance but is being referenced during the rendering process

Here is my custom Vue component: Vue.component("product-list", { props: ["products", "maximum-price"], template: ` <div> <div class="row d-flex mb-3 align-items-center p-3 rounded-3 animate__animate ...

Issue with Material-ui IconButton's edge properties not functioning as expected

Is there a way to position the delete icon on the right side of the screen? It seems like using edge= "end" is not working as expected. If you'd like to take a look, here is the sandbox link: https://codesandbox.io/s/admiring-silence-vwfoe? ...

Easy Steps to Simplify Your Code for Variable Management

I currently have 6 tabs, each with their own object. Data is being received from the server and filtered based on the tab name. var a = {} // First Tab Object var b = {} // Second Tab Object var c = {} // Third Tab Object var d = {}// Fou ...

Utilizing $dataprovider in Yii2 to efficiently return JSON Data

I'm trying to figure out how to return the $dataProvider in JSON format in Yii2. Here is the code I have: public function actionIndex() { $searchModel = new DraftSearch(); $dataProvider = $searchModel->search(Yii::$app->request->quer ...

The art of posting with ExpressJS

I'm encountering a problem where the data submitted through a form to my POST route is not getting passed on to a database document, even though the redirection works fine. I'm unsure of how to troubleshoot this issue. blogpost-create.ejs &l ...

What are the steps to create a dynamic Ajax Loading view?

I have encountered this situation multiple times, but unfortunately, I have not been able to find a simple solution or a website that explains the process and reasoning behind it. My goal is to create a container (div) that includes both a loading element ...