I am trying to retrieve info from an object but I can't seem to get it in the correct order. Doing it this way, total
is always equal to null
.
How do I ensure ensure that the total
is always filled before calculating the average?
you can see here that y remains undefined
$(function () {
var data =[];
var time =[];
var abc =[
{"val":"2015-07-02 03:55:00","name":"TIME_STAMP"},
{"val":"19981","name":"TOTAL"},
{"val":"2051","name":"\"A\""},
{"val":"274","name":"\"B\""},
{"val":"8826","name":"\"C\""},
{"val":"5351","name":"\"D\""},
{"val":"2628","name":"\"E\""},
{"val":"501","name":"\"F\""},
{"val":"350","name":"\"G\""},
{"val":" ","name":"\"H\" "}];
var total = null;
$.each(abc,function(i,el){
if (el.name == "TIME_STAMP") {
time.push({ name: el.name, y: parseInt(el.val) });
}
else if (el.name == "TOTAL") {
total = parseInt(el.val);
}
else if (total != null) {
var p = parseFloat(el.val) / total * 100;
data.push({name: el.name, y: p});
console.log(el.name + " " + el.y);
}
});
});
Change this line...
console.log(el.name + " " + el.y);
to this...
console.log(el.name + " " + p);
There is no el.y
.
Alternatively, create el.y
instead of p
...
$.each(abc,function(i,el){
if (el.name == "TIME_STAMP") {
time.push({ name: el.name, y: parseInt(el.val) });
}
else if (el.name == "TOTAL") {
total = parseInt(el.val);
}
else if (total != null) {
el.y = parseFloat(el.val) / total * 100;
data.push({name: el.name, y: el.y});
console.log(el.name + " " + el.y);
}
});
Adding this check fixed it.
$.each(json, function(i,el){
if (el.val != " "){
if(el.name == "TIME_STAMP" || el.name == "TOTAL"){
excess.push({name: el.name, y: parseInt(el.val)});
}else{
endData.push({name: el.name, y: parseInt(el.val)});
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.