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
134k13 gold badges168 silver badges171 bronze badges
asked May 24, 2015 at 14:09
George Moldovan
831 silver badge8 bronze badges
3 Answers 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()
});
});
answered May 24, 2015 at 14:12
Satpal
134k13 gold badges168 silver badges171 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
George Moldovan
but how can I access after the ajax event ? if I put a console log it said me that is undefined ?
Satpal
@GeorgeMoldovan, A of AJAX stands for asynchronous go through stackoverflow.com/questions/14220321/… , Its a good read and will provide solution for your problem
Andrea Mattioli
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.
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++;
});
answered May 24, 2015 at 14:12
James Newton
7,17210 gold badges55 silver badges129 bronze badges
Comments
Before pieData[i].value .., you should first have a line:
pieData[i] = {};
answered May 24, 2015 at 14:11
downhand
3951 gold badge9 silver badges23 bronze badges
Comments
lang-js