Hi there, I am currently working with an AJAX call and have the following code:
$.each(data.my_json, function(i, item) {
const op_id = item.op_id;
const op_name = item.op_name;
let nv_tmp_totals = item.nv_tmp_totals;
let nvc_tmp_totals = item.nvc_tmp_totals;
let iniz_totals = item.iniz_totals;
let deft_totals = item.deft_totals;
let rmkt_totals = item.rmkt_totals;
let nv_tmp_average = item.nv_tmp_average;
let nvc_tmp_average = item.nvc_tmp_average;
let iniz_average = item.iniz_tmp_average;
let deft_average = item.deft_tmp_average;
let rmkt_average = item.rmkt_tmp_average;
})
I want to optimize my code by using a loop for assigning variables. Currently, the code is repetitive and not efficient.
const source = ['rmkt', 'iniz', 'deft','nvc_tmp','nv_tmp'];
$.each(data.my_json, function(i, item) {
const op_id = item.op_id;
const op_name = item.op_name;
for (let i=0; i<source.length; i++) {
window[source[i]+"_totals"] = parseFloat(item.source[i]+"_totals")
window[source[i]+"_average"] = parseFloat(item.source[i]+"_average")
}
})