I am currently working on extracting data from a spreadsheet and storing it in an array. After storing the data in JavaScript variables, I need to store these variables as an object in my array. Below is the code snippet:
this.json = function(){
jQuery.getJSON("http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1l4XTKaLZihj5WDRuZJE5Y7RQ7Cr7SD_-tH0ctwhizWc/od6/public/values?alt=json").success(function(data) {
console.log(data.feed.entry);
for (var i = 0; i < data.feed.entry.length; i++) {
var id = data.feed.entry[i].gsx$id.$t;
var name = data.feed.entry[i].gsx$name.$t;
var price = data.feed.entry[i].gsx$price.$t;
var notcompatiblewith = data.feed.entry[i].gsx$notcompatiblewith.$t;
this.parts[i] = {"id": id, "name": name, "price": price, "comp": notcompatiblewith, "canAdd": true, "added": false};
};
});
};
I invoke the function this.json in my HTML using ng-init="myctrl.json()" and it works perfectly. However, when I check the console on inspect element, I encounter the error: 'Uncaught TypeError: Cannot set property '0' of undefined'
The desired formatting of my array upon initialization:
{
id: 1,
name: 'vitamine A',
price: 3,
canAdd: true,
added: false,
comp: [2, 5]
},
{
id: 2,
name: 'vitamine B',
price: 5,
canAdd: true,
added: false,
comp: [1, 3]
},
{
id: 3,
name: 'vitamine C',
price: 2,
canAdd: true,
added: false,
comp: [2]
},
{
id: 4,
name: 'Opium',
price: 20.95,
canAdd: true,
added: false,
comp: []
},
{
id: 5,
name: 'steroids',
price: 12.5,
canAdd: true,
added: false,
comp: [1]
}
Edit: The array parts is initialized under my controller as shown below:
var parts = [];
and declared in my controller like this:
this.parts = parts;