George Moldovan
George Moldovan

Reputation: 83

Creating objects dynamically in javascript issue

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

Upvotes: 0

Views: 53

Answers (3)

James Newton
James Newton

Reputation: 7082

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++;
});

Upvotes: 2

Satpal
Satpal

Reputation: 133403

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()
    });
});

Upvotes: 3

downhand
downhand

Reputation: 395

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

pieData[i] = {};

Upvotes: 1

Related Questions