0

Hi trying to create this array dynamically. This is the static way:

var pieData = [
                {
                    value: 300,
                    color:getRandomColor(),
                    highlight: getRandomColor(),
                },
                {
                    value: 50,
                    color: getRandomColor(),
                    highlight: "#fac878",
                },
                {
                    value: 100,
                    color: getRandomColor(),
                    highlight: getRandomColor(),
                },
                {
                    value: 120,
                    color: getRandomColor(),
                    highlight: getRandomColor(),
                }

            ];

This is what I achieved:

$.ajax({
        method: "POST",
        url: "getPieChartData"
    })
    .done(function(data){
        obj  = $.parseJSON(data);
        var pieData = []; i = 0;
        $.each(obj, function(key, item) {
            pieData[i].value = item.total + " - " + item.d_name;
            pieData[i].color = getRandomColor();
            pieData[i].highlight = getRandomColor();
            i++;
        });
    });

I am getting value from my function that is not a problem. My issue is that I am getting in the console that this part:

pieData[i].value = item.total +" - " + item.d_name; TypeError: pieData[i] is undefined

What am I doing wrong? thx

Satpal
  • 132,252
  • 13
  • 159
  • 168

3 Answers3

3

You can simple use .push() method. No meed to use indexer.

The push() method adds one or more elements to the end of an array and returns the new length of the array.

$.each(obj, function(key, item) {
    pieData.push({
        value: item.total + " - " + item.d_name,
        color : getRandomColor(),
        highlight : getRandomColor()
    });
});
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • but how can I access after the ajax event ? if I put a console log it said me that is undefined ? – George Moldovan May 24 '15 at 14:26
  • @GeorgeMoldovan, __A__ of AJAX stands for asynchronous go through http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call , Its a good read and will provide solution for your problem – Satpal May 24 '15 at 14:31
  • This code works good, but "push" isn't the solution of the problem. The solution IS the new object passed to push, but you can do it without push too, like @James Newton wrote in his answer. – Andrea Mattioli May 25 '15 at 06:35
2

You need to create the pieData[i] object first;

var pieData = []; i = 0;
$.each(obj, function(key, item) {
    pieData[i] = {}; // added line
    pieData[i].value = item.total + " - " + item.d_name;
    pieData[i].color = getRandomColor();
    pieData[i].highlight = getRandomColor();
    i++;
});
James Newton
  • 6,623
  • 8
  • 49
  • 113
1

Before pieData[i].value .., you should first have a line:

pieData[i] = {};
downhand
  • 395
  • 1
  • 9
  • 23