Cannot set property '0' of 2D array - javascript

Can anyone tell me why I'm getting this error for the code below:
Uncaught TypeError: Cannot set property '0' of undefined
var vehicles = [];
$.get('../poll/index.php?data=vehicles', function(data) {
var rows = $(data).find('row').length;
for (var i = 0; i < rows; i++) {
vehicles[i][0] = $(data).find('row').eq(i).find('stage').text();
vehicles[i][1] = $(data).find('row').eq(i).find('direction').text();
vehicles[i][2] = $(data).find('row').eq(i).find('stageName').text();
vehicles[i][3] = $(data).find('row').eq(i).find('atco').text();
vehicles[i][4] = $(data).find('row').eq(i).find('service').text();
vehicles[i][5] = $(data).find('row').eq(i).find('journey').text();
vehicles[i][6] = $(data).find('row').eq(i).find('fleet').text();
vehicles[i][7] = $(data).find('row').eq(i).find('longitude').text();
vehicles[i][8] = $(data).find('row').eq(i).find('latitude').text();
vehicles[i][9] = $(data).find('row').eq(i).find('operator').text();
vehicles[i][10] = $(data).find('row').eq(i).find('position').text();
}
}, 'xml');

You need to define each child array, e.g.
var vehicles = []; // parent array;
vehicles[0] = []; // first child array;
so you would need:
for (var i = 0; i < rows; i++) {
var vehicles[i] = [];
... rest of code here ...
}

vehicles[i] has no value assigned to it.
Add a line:
vehicles[i] = [];
at the top of the loop.

Related

Having Trouble Parsing Results of Array

I'm having a bit of trouble trying to parse the results of an array and print to the console. It's a two part problem actually. When I build the array it's adding "undefined" to the results. When I try to loop through the individual strings in the array it isn't parsing, just returning the full array object.
What I'm trying to do is collect all the field values selected from a list view and write them to another child list as separate items. When displaying results in a console it shows as an object array. When I run the typeof method against it I believe it shows as a string.
To reiterate, why am I getting undefined and why is my array not printing to console correctly. Below is an example of what is being returned thus far (when two records are selected) and my code.
Results:
undefinedDaffy DuckBugs Bunny
undefined
Code:
// Grabs selected items from getSelected function and passes parameters to writeSelected function
function callAccepted() {
getSelected().done(function(varObjects) {
for (var k in varObjects) {
console.log(varObjects[k]);
}
}); // End getSelected
} // End callAccepted
// Grabs selected items, accepts input from callAccepted or callRejected functions
function getSelected() {
var dfd = $.Deferred(function(){
var ctx = SP.ClientContext.get_current();
var clientContext = new SP.ClientContext();
var targetList = clientContext.get_web().get_lists().getByTitle(ListName);
var SelectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
var items = [];
var arrItems = [];
for (var i in SelectedItems) {
var id = SelectedItems[i].id;
var item = targetList.getItemById(id);
clientContext.load(item, "Title");
items.push(item);
} // End for
clientContext.executeQueryAsync(
function(){ // Return to button click function
var itemLength = 0;
var itemObjects = [];
for (var j = 0; j < items.length; j++) {
itemObjects = items[j].get_item("Title");
itemLength += itemObjects;
arrItems.push(itemObjects);
}
dfd.resolve(arrItems, itemLength);
},
function(){ // Return to button click function
dfd.reject(args.get_message());
}
); // End ClientContext
}); // End dfd
return dfd.promise();
} // End getSelected
Why are you writing "var itemObjects;" in 1 line and add one string "itemObjects += items[j].get_item("Title");" in another? There'll be only 1 string anyway, so when you change those 2 lines into one, "undefined" should disappear:
function callAccepted() {
getSelected().done(function(varObjects, iLength) {
// Stuff
for (var k = 0; k < iLength; k++) {
console.log(varObjects[k]);
}
}); // End getSelected
} // End callAccepted
// Get user information function
function getSelected() {
var dfd = $.Deferred(function(){
var ctx = SP.ClientContext.get_current();
var clientContext = new SP.ClientContext();
var targetList = clientContext.get_web().get_lists().getByTitle(ListName);
var SelectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
var items = [];
var arrItems = [];
for (var i in SelectedItems) {
var id = SelectedItems[i].id;
var item = targetList.getItemById(id);
clientContext.load(item, "Title");
items.push(item);
} // End for
clientContext.executeQueryAsync(
function(){ // Return to button click function
for (var j = 0; j < items.length; j++) {
var itemObjects = items[j].get_item("Title");
var itemLength = items.length;
arrItems.push(itemObjects);
}
dfd.resolve(arrItems, itemLength);
},
function(){ // Return to button click function
dfd.reject(args.get_message());
}
); // End ClientContext
}); // End dfd
return dfd.promise();
} // End getSelected
The reason for this is that after creating the variable without any value, it's undefined, so += 'Unicorn' will give us ugly 'UndefinedUnicorn'. If you wish to make variable for this purpose, write it "var x = ''".
And if - for example - you want to sum length of all "items", then this one function should look like:
function(){ // Return to button click function
var itemLength = 0;
for (var j = 0; j < items.length; j++) {
var itemObjects = items[j].get_item("Title");
itemLength += itemObjects;
arrItems.push(itemObjects);
}
dfd.resolve(arrItems, itemLength);
}
But I'm not exactly sure what are you trying to get here.

Getting trouble while trying Dynamic Data in jsPdf AutoTable

Am trying to print the dynamic data into the PDF using jsPdf AutoTable .But am failed to do that. I searched in many site's but no one didn't said about dynamic data into the Row's. So here my question is , Is there any way to get the Dynamic data into the table row's if it so can some one clarify me pls . Note : [ Here am not using HTML to store the Data into the Pdf, i got the data from the js directly ] .
this.print=function(){
{
var mainData =this.printData(); // Here am getting Full Json data Here
var steps = mainData.steps; // From that data am Separating what i need
var criticality = mainData.criticality;
var categories = mainData.categories;
var checkup = mainData.checkup;
// This is For to Take the Steps Data alone
$scope.getSteps = function(steps) {
var data = [];
for (var i = steps.length; i-- > 0;) {
data.push(steps[i].name+"\n"+"\n");
}
return data;
}
// Like wise am getting every single object data's
$scope.getNumbersOfSubSteps = function(steps) {
var data = 0;
for (var i = 0 ; i < steps.length; i++) {
for (var j = 0; j<steps[i].steps.length; j++) {
}
data = j ;
}
return data;
}
// this is for Sub Proceeses
$scope.getSubProcesses = function(steps) {
var data = [];
for (var i = 0 ; i < steps.length; i++) {
for (var j = 0; j<steps[i].steps.length; j++) {
data.push(steps[i].steps[j].name+"\n");
}
}
return data;
}
$scope.getCategories = function(categories) {
var data = [];
for (var i = categories.length; i-- > 0;) {
data.push(categories[i].name+"\n");
}
return data;
}
$scope.getCriticality = function(criticality) {
var data = [];
for (var i = criticality.length; i-- > 0;) {
data.push(criticality[i].name+"\n");
}
return data;
}
// Pdf Print Function Begins
var columns = ["ProcessDescription", "Steps", "#ofSubProcesses", "SubSteps","Category","Criticality","CheckUp"];
var processDescription =mainData.description;
var processes= $scope.getSteps(steps);
var NoOfSubProcess = $scope.getNumbersOfSubSteps(steps);
var subProcesses = $scope.getSubProcesses(steps);
console.log('Subprocsses length',subProcesses);
var categories = $scope.getCategories(categories);
var criticality = $scope.getCriticality(criticality);
// The Problem Begins here , Am struggling to Get the Separate data's here !
var rows = [
[processDescription,processes,NoOfSubProcess,subProcesses,categories,criticality]
];
var pdfsize='a1';
var doc = new jsPDF('p', 'pt',pdfsize);
doc.autoTable(columns, rows, {
theme: 'striped', // 'striped', 'grid' or 'plain'
styles: {
overflow: 'linebreak',
columnWidth: 'wrap'
},
beforePageContent: function(data) {
doc.text("Process Name :"+mainData.name, 40, 30);
},
columnStyles: {
1: {columnWidth: 'auto'}
}
});
doc.save(mainData.name+ pdfsize +".pdf");
}
};
You will need to replace this:
var rows = [
[processDescription,processes,NoOfSubProcess,subProcesses,categories,criticality]
];
with something like this:
var rows = [];
for (var k = 0 ; k < processes.length; k++) {
rows.push([
processDescription,
processes[k],
NoOfSubProcess,
subProcesses[k],
categories[k],
criticality[k]
]);
};
The rows parameter should be an array of arrays. What you are putting in there is basically an array of an array of arrays if I understood correctly.

I'm adding only the last element to the JS array

Here is my code so far: I am trying to create a new JSON object called dataJSON using properties from the GAJSON object. However, when I try to iterate over the GAJSOn object, I get only its last element to be added to the array.
var GAstring ='{"data":[{"bounceRate": "4","country":"Denmark"},{"bounceRate":
"3","country":"Spain"},{"bounceRate":"6","country":"Romania"},
{"bounceRate":"1","country":"Bulgaria"},{"bounceRate":"0","country":"Lithuania"},
{"bounceRate":"2","country":"Norway"}]}';
var GAJSON=JSON.parse(GAstring);
var viewJSON = {
data:[]
};
var dataJSON ={};
for(var i =0; i<GAJSON.data.length; i++) {
dataJSON["bounceRate"] = GAJSON.data[i].bounceRate;
dataJSON["country"] = GAJSON.data[i].country;
}
viewJSON.data.push(dataJSON);
Your push of the new object should be within the loop.
for(var i =0; i<GAJSON.data.length; i++) {
viewJSON.data.push({
bounceRate: GAJSON.data[i].bounceRate,
country: GAJSON.data[i].country
});
}
DEMO
You are overwriting values every time at dataJSON["bounceRate"] = GAJSON.data[i].bounceRate;
Try this code:
var GAstring ='{"data":[{"bounceRate": "4","country":"Denmark"},{"bounceRate":"3","country":"Spain"},{"bounceRate":"6","country":"Romania"}, {"bounceRate":"1","country":"Bulgaria"},{"bounceRate":"0","country":"Lithuania"}, {"bounceRate":"2","country":"Norway"}]}';
var GAJSON=JSON.parse(GAstring);
var viewJSON = {
data:[]
};
var dataJSON ={};
for(var i =0; i<GAJSON.data.length; i++) {
dataJSON[i] = [];
dataJSON[i]["bounceRate"] = GAJSON.data[i].bounceRate;
dataJSON[i]["country"] = GAJSON.data[i].country;
}
viewJSON.data.push(dataJSON);
console.log(viewJSON);
DEMO

Get Unique values during Loop

I am looping through an array and getting the data that I need.
for (var i = 0; i < finalArray.length; i++) {
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
var transAccount = finalArray[i].transAccount;
}
What I am trying to do at this point is only show unique data in the loop.
For example var transAccount could be in the array 5 times. I only one to display that in my table once. How can I go about accomplishing this ?
Final Array is constructed like so; just as an object:
finalArray.push({
transID: tmpTrans,
transAccount: tmpAccount,
amEmail: amEmail,
merchName: merchName,
amPhone: amPhone,
amName: amName
});
var allTransAccount = {};
for (var i = 0; i < finalArray.length; i++) {
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
var transAccount = finalArray[i].transAccount;
if(allTransAccount[finalArray[i].transAccount]) {
var transAccount = '';
}
else {
allTransAccount[transAccount] = true;
}
}
var merhcData = {};
var amName = {};
// and so on
for (var i = 0; i < finalArray.length; i++) {
merchData[finalArray[i].merchName] = finalArray[i].merchName;
amName[finalArray[i].amName] = finalArray[i].amName;
// and so on
}
If you are sure, that data in merchName will never be equal amName or other field - you can use one data object instead of several (merchData, amName...)
What you want is likely a Set. (see zakas for ES6 implementation. To emulate this using javascript, you could use an object with the key as one of your properties (account would be a good bet, as aperl said) which you test before using your raw array.
var theSet={};
for (var i = 0; i < finalArray.length; i++) {
var transAccount = finalArray[i].transAccount;
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
if(!theSet[transAccount]){
//add to your table
theSet[transAccount]===true;
}
This will prevent entries of duplicate data.

Problems with multidimensional array and loops

This script crashes randomly with the message "unable to get property .length of undefined or null reference" referring to "matched_array_pics.length". It crashes for sure if I clone, append the same image twice to the #train div.
$(document).ready(function () {
var starting_pics = ["AN.gif", "CN.gif", "EN.gif", "GN.gif"];
var an_array_pics = ["CN.gif", "EN.gif", "GN.gif", "AN.gif"];
var cn_array_pics = ["EN.gif", "GN.gif", "AN.gif", "CN.gif"];
var en_array_pics = ["GN.gif", "AN.gif", "CN.gif", "EN.gif"];
var gn_array_pics = ["AN.gif", "CN.gif", "EN.gif", "GN.gif"];
var grand_array_pics = [an_array_pics, cn_array_pics, en_array_pics, gn_array_pics];
var i = 0;
for (i = 0; i < starting_pics.length; i++) {
$("<img/>").attr("src", "images/" + starting_pics[i]).load(function () {
$(this).appendTo("#main");
$(this).addClass("pics");
});
}
$("#main").on("click", ".pics", function () {
var j = $(".pics").index(this); // gets the index for the matched_array_pics...
console.log(j);
$("#sidebar .pics").remove();
$(this).clone().appendTo("#train");
$(this).clone().appendTo("#sidebar");
$("#main .pics").remove();
var matched_array_pics = grand_array_pics[j]; // ... in grand_array_pics.
var k = 0;
for (k = 0; k < matched_array_pics.length; k++) {
$("<img/>").attr("src", "images/" + matched_array_pics[k]).load(function () {
$(this).appendTo("#main");
$(this).addClass("pics");
});
}
});
}); //end ready
I think the problem is in this line: var j = $(".pics").index(this); and I think it should be rewritten like this: var j = $(this).index(); It'd be helpful if you could add console.log(j); just after the line in question to see what j ends up being. When this line executes var matched_array_pics = grand_array_pics[j]; I think you're getting undefined because j is not a number when your code runs.

Categories

Resources