I am using p5 loadJSON to import data, the data gives an array with so many records and sub-arrays.
For example, data.records[i].form_values["94d5"] gives me a name.
I am currently using a for loop to go through data.records.length and give me an array of some key pieces of data relative to each record I want to see.
Problem:
I want to loop through the records and get the value of:
data.records[i].form_values["94d5"].choice_values["0"], but some records don't have form_values["94d5"], for example. I just want to skip empty sections (leave undefined like empty items) insted i get an error that choice_values is undefined.
My loop is:
function gotData(data){
var i = 0;
var statusFind = data.records[i].status;
for(i = 0; i < data.records.length; i++) {
var returned = [data.records[i].form_values["6f71"], data.records[i].form_values.b059, data.records[i].form_values["94d5"], data.records[i].form_values.b62d, data.records[i].form_values["3493"].choice_values["0"], data.records[i].status, data.records[i].form_values.af80];
for (j = 0; j < returned.length; returned++){
if (returned[j] == searchKey) {
var result = [returned[0], returned[1], returned[2], returned[3], returned[4], returned[5], returned[6]];
array.push(result);
write();
}
}
}
}
Related
What I am trying to do is:
set an array value (list) to another array (options).
If the user's input (searchVal) matches with a list value it will delete options, push this match, and then will keep pushing the next matches without deleting options again.
So according to the code below, if searchVal was "whatever", options should return: ["whatever", "whatevEver1"] but, instead, it returns: ["whatever", "WhatEver1", "whatttever", "whatever", "whatevEver1"]
Relevant code:
var list = ["whatever", "WhatEver1", "whatttever"];
var clear = 0;
var options = [];
for (var i=0 ; i < list.length ; i++)
{
options.push([list[i]]);
}
var searchVal = window.prompt(" ");
for (var i=0 ; i < list.length ; i++)
{
if (list[i].toLowerCase().includes(searchVal.toLowerCase())) {
if (clear == 0) {
options.length = 0;
}
options.push([list[i]]);
}
clear++;
}
return options;
Js arrays are pass-by-reference. In order to make independent copy of array you need to use:
let options = JSON.parse(JSON.stringify(list));
I didnt try to implement this to your problem cause im too lazy but i think it might work.
I am programming a task-switching experiment in javascript using the jsPsych library (jsPsych 6.0.5). I use a predefined list with stimulus attributes but I can't seem to link the specific values to variables in the data argument (output of data is undefined).
I am using a for-loop to link these values to the data argument, but that doesn't seem to be working. In the sample here below the first for-loop reads in the different columns of the predefined list, with each row representing a single trial. In the second for-loop, I try to input these values for each trial (row) to the data argument of my test_stimuli
for(this_trial = 0; this_trial < blocks[0].length; this_trial ++){
curr_trial = blocks[0][this_trial];
modality[this_trial] = curr_trial[6];
cresp[this_trial] = curr_trial[10];
perc_stim[this_trial] = [];
for(j = 0; j < 4; j++){perc_stim[this_trial][j] = curr_trial[11 + j];};
probe[this_trial] = curr_trial[15];
condition[this_trial] = curr_trial[16];
}
for (i = 0; i < blocks[0].length; i++) {
test_stimuli[i] = [{
image: `<img src="images_a/${perc_stim[i][0]}.bmp" class = "training1"/>`,
data: {
correct_response: [cresp[i]],
modality: modality[i],
trial_id: 'stim'
}
}];
}
When I log the data argument to the console, I get "undefined" (even though it logs the correct values when looking at for example the cresp array).
My code yields the following error:
Uncaught TypeError: Cannot set property '0' of undefined
First, here's the screenshot of the table
Note:
This table are the assigned work schedule of the student.
Let's proceed to my code:
function saveWorkSched(){
// listWorkSched
var arr=[];
var getSAWorkSched=[[],[]];
var wsCounter=0;
var wsCounter2=0;
var j = 0;
$("#listWorkSched td").each(function(){
arr.push($(this).text());
});
console.log(arr);
for(j;j<arr.length;j++){
if(wsCounter2<=2){
getSAWorkSched[wsCounter][wsCounter2]=arr[j];
wsCounter2++;
}else{
wsCounter++;
wsCounter2=0;
getSAWorkSched[wsCounter][wsCounter2]=arr[j];
wsCounter2++;
}
}
}
1st phase:
after the user create the work schedule this will be stored in arr variable.
2nd phase:
the arr value will converted to multi-dimensional array and will be stored in getSAWorkSched variable
after the 3rd loop an error will occurred. it means that every time I create a work schedule more than 2 the error will trigger.
else{
wsCounter++;
wsCounter2=0;
getSAWorkSched[wsCounter][wsCounter2]=arr[j]; // Here's the code where the error specified based on the console of my browser
wsCounter2++;
}
You need to define the nested array that you try to access. It really comes down to the same principle: you address the following:
getSAWorkSched[wsCounter][wsCounter2]
... with a wsCounter value that is eventually getting to 2, but you have only defined two nested arrays in the initialisation of getSAWorkSched, so getSAWorkSched[2] does not exist -- it will give you undefined. Trying to get an array element from nothing (undefined) is not possible. So add this line before it in the else bock:
getSAWorkSched[wsCounter] = []; // <--- Add this
getSAWorkSched[wsCounter][wsCounter2]=arr[j];
More elegant code
You could use $.map and slice to write this in a more elegant way:
function saveWorkSched() {
var arr = $.map($("#listWorkSched td"), function (td) {
return $(td).text();
});
var getSAWorkSched = [];
for (var j = 0; j < arr.length; j += 3) {
getSAWorkSched.push(arr.slice(j, j + 3));
}
}
Meet with a really weird javascript problem. See my codes below:
function initBadScripts(controlArray) {
var scriptsLine = prompt("Please enter the bad scripts", "debug");
if (scriptsLine != null) {
var pattern = /;/;
var nameList = scriptsLine.split(pattern);
alert(nameList+" "+nameList.length);
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter][0]=true;
controlArray[counter][1]= new RegExp(nameList[counter],"g");
alert(controlArray[counter][0]);
}
}
alert("wtf!");
}
var controlArray = [[]];
initBadScripts(controlArray);
I defined a function, and call that function. A 2-dimensional array called 'controlArray' is defined with no value. Basically, the function check the user's input and use regular expression to make a 'namelist'. For example, if the user type in
ExampleOne;ExampleTwo
The function will create an array called 'nameList'
nameList=[ExampleOne,ExampleTwo];
Then I want to make a dynamical initialization of the 2-dimensional array called 'controlArray', according to the length of nameList. However this only works fine the nameList'length is 1. If it exceeds one (the user type in 'ExampleOne;ExampleTwo'), the ExampleTwo does not go into the array, and the
alert("wtf");
doesn't run at all. This seems that there is already an error before it. Any comments?
JavaScript doesn't have a true 2-dimensional array. Rather, you're putting a second array inside the first array. Change it to this:
...
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter] = [true, new RegExp(nameList[counter],"g")];
...
Yes or you declare your variable like that:
var controlArray = [[],[]];
or
var controlArray = new Array(2);
for (var i = 0; i < 2; i++) {
controlArray[i] = new Array(2);
}
var AppPatientsList = JSON.parse(JSON RESPONSE);
var AppPatientsListSort = AppPatientsList.sort(function(a,b){
return a.firstName.toLowerCase() <b.firstName.toLowerCase()
? -1
: a.firstName.toLowerCase()>b.firstName.toLowerCase()
? 1 : 0;
});
var DataArray = [];
for (var i = 0; i < AppPatientsListSort.length; ++i) {
if (AppPatientsListSort[i].firstName === search.value) {
var appointment = {};
appointment.PatientID = AppPatientsListSort[i].PatientID;
appointment.ScheduleDate = AppPatientsListSort[i].ScheduleDate;
alert(appointment.ScheduleDate); // Works fine, i get the date...
}
DataArray[i] = appointment;
}
var RowIndex = 0;
var ScheduleDate = "";
for (i = 0, len = DataArray.length; i < len; i++) {
// Throws me error in this place... WHY?
if (ScheduleDate != DataArray[i].ScheduleDate) {
ScheduleDate = DataArray[i].ScheduleDate;
}
}
What's wrong with this code, why i am not able to access the ScheduleDate?
You are only initializing the appointment variable when you are inside the if clause, but you are adding it to the array on every iteration.
If the first element of AppPatientsListSort does not have the value you search for, DataArray[0] will contain undefined.
In the second loop you then try to access DataArray[0].ScheduleDate which will throw an error.
Update:
Even more important, as JavaScript has no block scope, it might be that several entries in DataArray point to the same appointment object.
Depending on what you want to do, everything it takes might be to change
DataArray[i] = appointment;
to
DataArray.push(appointment);
and move this statement inside the if clause so that only appointments are added that match the search criteria.
Further notes: To have a look what your DataArray contains, make a console.dir(DataArray) before the second loop and inspect the content (assuming you are using Chrome or Safari, use Firebug for Firefox).