Cannot read property ScheduleDate from undefined - javascript

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).

Related

How can I delete array elements just once to add new ones with a for loop

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.

JSON for-loop that ignores blank sub arrays

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();
}
}
}
}

How to simplify this delete from array jQuery

I have an object and an array of categories that should be kept in the object. This snip https://jsfiddle.net/h10rkb6s/2/ ( see log ) works but I cant seems to shake the idea that it is to complicated for a simple search and keep task.
var thz_icon_source = {"Spinners":["spinnericon1","spinnericon2"],"Awesome":["awesomeicon1","awesomeicon2"],"Others":["othericon1","othericon2"]};
var $categories = '["Spinners","Awesome"]';
var $CatsArray = JSON.parse($categories);
var groups = [];
for(var k in thz_icon_source) groups.push(k);
$.each($CatsArray,function(i,keep){
var index = groups.indexOf(keep);
if (index !== -1) {
groups.splice(index, 1);
}
});
for (var i = 0; i < groups.length; i++) {
delete thz_icon_source[groups[i]];
}
I tried with
$.each(thz_icon_source,function(category,icons){
$.each($CatsArray,function(i,keep){
var index = category.indexOf(keep);
if (index !== -1) {
delete thz_icon_source[category];
}
});
});
but this works only if 1 item is inside my search array.
Any help is appreciated.
There's no need to iterate over $CatsArray to find out which ones should be deleted. You will need to iterate over the keys of the object, and find out for each of them whether it should be deleted, to filter by that.
Leaving the top 3 lines of your script intact, you could simplify to
var keysToDelete = Object.keys(thz_icon_source).filter(function(groupName) {
return $CatsArray.indexOf(groupName) == -1;
});
($.grep would be the jQuery-ism for the filter method, if you are into that).
But assuming we don't even need those groups in an array, you could simply do
for (var groupName in thz_icon_source)
if ($CatsArray.indexOf(groupName) == -1)
delete thz_icon_source[groupName];
However, instead of deleting items from that object, I'd recommend to create a new object with only those that you want to keep. It's much easier to use:
var kept = {};
for (var i=0; i<$CatsArray.length; i++)
kept[$CatsArray[i]] = thz_icon_source[$CatsArray[i]];

associative array not setting correctly

i'm new to javascript and jquery and was wondering if someone could let me in on why this isn't working correctly.
i have a drop-down box that a user selects a value from, then "Processes." When processed the value of the drop-down as well as a textbox is stored in an array. I want the user to be able to then basically store the same drop-down selection and textbox data in the array again but now in a new value pair.
First store would be
TestArray[0][0] = "Textbox Value"
If "Processed" again, it would be
TestArray[1][0] = "Textbox Value"
that way I can parse through later and figure how many times the user "Processed" the drop-down selection;
var oneClickReport = $("#reportName").val();
if(oneClickReport == "Sample Report One"){
var arrayOneCount = reportOneArray.length;
var totalHouseholds = 0;
$("#reportChecks span:visible").each(function(){
if($(this).find(':checkbox').prop('checked')){
var HHName = $(this).text();
reportOneArray.push(HHName);
arrayTest[arrayOneCount][totalHouseholds] = HHName;
}
totalHouseholds += 1;
});
for(i = 0; i < arrayOneCount; i+=1){
alert(arrayTest[0][i]);
}
}
But when trying to "Process" for the second time, I receive the error of;
SCRIPT5007: Unable to set property '0' of undefined or null reference
on line;
arrayTest[arrayOneCount][totalHouseholds] = HHName;
You need to initialize your array. I'm not sure what exactly you want to do but you need an array like this
var arrayTest = []
And you will need to initialize subsequent value like
arrayTest[1] = []
Then you can access your array
arrayTest[1][0] = []
I made an example for you
var oneClickReport = $("#reportName").val();
var arrayTest = [] # You may need to put this elsewhere
if(oneClickReport == "Sample Report One"){
var arrayOneCount = reportOneArray.length;
var totalHouseholds = 0;
$("#reportChecks span:visible").each(function(){
if($(this).find(':checkbox').prop('checked')){
var HHName = $(this).text();
reportOneArray.push(HHName);
if(!arrayTest[arrayOneCount]){ arrayTest[arrayOneCount] = []; }
arrayTest[arrayOneCount][totalHouseholds] = HHName;
}
totalHouseholds += 1;
});
for(i = 0; i < arrayOneCount; i+=1){
alert(arrayTest[0][i]);
}
}
your problem with var arrayOneCount = reportOneArray.length; and you're not changing this value

extract elements from two arrays with same value

Hello I want to extract elements from both arrays with the same url .How can i loop these two arrays and get their content, because it gives me undefined for the news_url and i think it outputs twice the items in the console.
function geo(news_array,user_tweets){
console.log(news_array,user_tweets);
for (var x=0; x<user_tweets.length; x++) {
var user = user_tweets[x].user;
var date = user_tweets[x].date;
var profile_img = user_tweets[x].profile_img;
var text = user_tweets[x].text;
var url=user_tweets[x].url;
second(user,date,profile_img,text,url);
}
function second(user,date,profile_img,text,url){
for (var i = 0; i < news_array.length; i++) {
var news_user = news_array[i].news_user;
var news_date = news_array[i].news_date;
var news_profile_img = news_array[i].news_profile_img;
var news_text = news_array[i].news_text;
var news_url=news_array[i].url;
if (url==news_array[i].news_url) {
geocode(user,date,profile_img,text,url,news_user,news_date,news_profile_img,news_text,news_url);
}
}
}
function geocode(user,date,profile_img,text,url,news_user,news_date,news_profile_img,news_text,news_url) {
console.log(url,news_url);
}
}
The problem is
in news_tweets function, you add news_url to news_array. So you should call
news_array[i].news_url
in second function.
I modify your code as
news_url: (item.entities.urls.length > 0)?item.entities.urls[0].url : '' in news_tweets function
add close brace } for geo function and remove } from last
add new_array parameter to second function like second(user, date, profile_img, text, url,news_array);
Modify code can be tested in http://jsfiddle.net/rhjJb/7/
You have to declare some variables before the first for loop, so that they can be accessed in the scope of the second function. Try to replace your first for loop with the following code:
var user, date, profile_img, text, url;
for (var x=0; x<user_tweets.length; x++){
user = user_tweets[x].user;
date = user_tweets[x].date;
profile_img = user_tweets[x].profile_img;
text = user_tweets[x].text;
url=user_tweets[x].url;
second(user,date,profile_img,text,url);
}
Moreover, in the if of your second function, news_array[i].news_url isn't defined. Use if (url == news_url) instead.

Categories