Let's say we have a variable named var testVar = [];
and we receive data via ajax in the following format:
{
"Country": "ALA Aland Islands",
"CountryCode": "AX",
"Slug": "ala-aland-islands",
"Population": 100000,
"Teenagers": 50000,
"Mid": 20000,
"Seniors": 30000
},
{
"Country": "Afghanistan",
"CountryCode": "AFR",
"Slug": "afghanistan",
"Population": 200000,
"Teenagers": 50000,
"Mid": 100000,
"Seniors": 50000
}
We attempt to loop through this data and store the population per country in the array (testVar) using the following approach:
function obj(key, val) {
this.key = key;
this.val = val;
}
for(i=0;i<data.lenght;i++){
var x = new obj("y",data[i].Population);
testVar.push(x);
}
Although the above code snippet functions as intended, it does not generate the desired output. Our objective is for the data structure to look like this instead:
[{...}], [{...}] rather than [obj,obj]