How to check undefined variable javascript? - javascript

My Javascript is like this :
<script type="text/javascript">
var priceJson = '[{"#attributes":{"Code":"SGL","Total":"400000"},"DayPrice":{"Date":"2016-05-26","Rate":"400000"}},{"#attributes":{"Code":"DBL","Total":"200000"},"DayPrice":{"Date":"2016-05-26","Rate":"200000"}}]';
console.log(priceJson);
var priceObject = JSON.parse(priceJson);
console.log(priceObject);
if(priceObject.DayPrice.Rate)
priceObject = [priceObject];
else
priceObject = priceObject;
console.log(priceObject);
var priceJson = JSON.stringify(priceObject);
console.log(priceJson);
var countRoomType = priceObject.length;
for(var i=0; i<countRoomType; i++){
console.log(priceObject[i].DayPrice.Date);
console.log(priceObject[i].DayPrice.Rate);
}
</script>
Demo (See in console) : https://jsfiddle.net/oscar11/wsqdha8w/1/
Variable priceJson has a dynamic value. The value can be one single instance of data or can be an array of data. If the value contains 1 data then I convert into a data array like this:
if(priceObject.DayPrice.Rate)
priceObject = [priceObject];
But, in console there is the following error: TypeError: priceObject.DayPrice is undefined
Any solutions to solve my problem?

Judging by your error message, you need to check the existance of DayPrice also.
if( priceObject.DayPrice && priceObject.DayPrice.Rate )
This if condition has two steps.
First it checks if DayPrice exists,
Second it checks if DayPrice.Rate exists
It won't check second condition if first one fails

Related

jQuery - Take array of objects, then sort based on a dataset

I have a game I created that will add questions missed to my array missedArr, in my JSFiddle example, I have 2 buttons (both set to be wrong answers). After clicking these, it seems to have stored both clicks correctly, however I want give a readout at the end of the game to show my user what parts they did well on vs ones they did poorly on.
To do this, I created a function called determineScorecard which should serve to create a dict of my missedArr, however, when it goes to trigger I get undefined.
The dSc function should be sorting across the data-category set on the html buttons, then I want to console.log only the ones that were missed in category-2
function determineScorecard (){
//build dictionary for missed questions
var sortedMissed = {};
for( var i = 0, max = missedArr.length; i < max ; i++ ){
if( sortedMissed[missedArr[i].category] == undefined ){
sortedMissed[missedArr[i].category] = [];
}
sortedMissed[missedArr[i].category].push(missedArr[i]);
}
console.log(sortedMissed["2"]);
}
I can't seem to get this to split up correctly.
I think this is what you're trying to do:
var incorrect = [];
$('.answer').click(function(){
var data = $(this).data(),
correct = data.correct;
if(!data.correct){
incorrect.push(data);
determineScorecard();
}
});
function determineScorecard(){
var missed = {};
for(var i = 0, max = incorrect.length; i < max ; i++){
var question = incorrect[i];
if(!missed[question.category]){
missed[question.category] = [];
}
missed[question.category].push(question);
}
console.log(missed);
}
DEMO
However, I don't see how this can produce what you're expecting. The scorecard logic makes zero sense to me (with the code that's been provided). Can you post a complete example with the questions so we can see the entire flow?
Maybe you want something like this?
var missedArr = [];
$('.answer').click(function(){
var da=$(this).data();
if (da.correct) return false;
missedArr.push(da);
determineScorecard();
});
function determineScorecard (){
var sortedMissed = {};
$.each(missedArr,(i,da)=>{
if( sortedMissed[da.category] === undefined ){
sortedMissed[da.category] = [];
}
sortedMissed[da.category].push(da);
})
console.log(JSON.stringify(sortedMissed));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button class="btn btn-danger answer" data-category="2" data-question="2" data-value="300" data-correct="false">Google</button>
<button class="btn btn-danger answer" data-category="3" data-question="2" data-value="300" data-correct="false">Full-circle reporting</button>
In my solution I have not stored the whole buttonDOM elements but only their data()-objects into the sortedMissed array since these contain all the information about the question and button pressed. But if you don't like it, feel free to change that back again ...
Referencing your JSFiddle: The missedArr array contains DOM elements. To get the category, value, etc of that element you'll need to access the dataset property of the element.
missedArr[i].category // doesn't exist
missedArr[i].dataset.category // should exist
Updated for jQuery, which uses the .data() method:
missedArr[i].data('category') // should exist
When wrapping 'this' in the jQuery function like $(this), the element becomes a jQuery object, so to access the dataset use the .data() method rather than trying to access the properties directly like you would with vanilla JS:
// lines 22 - 24 of your JSFiddle
if( sortedMissed[missedArr[i].category] == undefined ){
sortedMissed[missedArr[i].category] = [];
}

How can I avoid "Cannot read property" error when the element isn't exist?

Here is my code:
category = $(document).find(".chosen-single:not(.chosen-default) > span:first-child")[0].outerHTML
Sometimes it throws:
Uncaught TypeError: Cannot read property 'outerHTML' of undefined
What kind of condition should I put on the way of that?
One nice trick is to use an anonymous function, like this, where you pass the query as a parameter
category = (function (el) {
return (el) ? el.outerHTML : '';
})($(document).find(".chosen-single:not(.chosen-default) > span:first-child")[0]);
It will save you setting up an extra variable and an if/then/else statement.
Make your code look something like this:
var element = $(document).find(".chosen-single:not(.chosen-default) > span:first-child")[0];
if(element) {
category = element.outerHTML
}
it's seems that sometimes the element you are searching is missing, so the result is undefined, to avoid this issue, check if found what you queried for
Either check the native DOM element or check the length of the jQuery object:
var obj = $(document).find(".chosen-single:not(.chosen-default) > span:first-child")[0];
var category = "";
if (obj) category = obj.outerHTML;
Checking the length:
var $obj = $(document).find(".chosen-single:not(.chosen-default) > span:first-child");
var category = "";
if ($obj.length) category = obj.outerHTML;
Just store the element in a variable, then check it before accessing:
var $chosenItem = $(document).find(".chosen-single:not(.chosen-default) > span:first-child")[0];
category = $chosenItem && $chosenItem.outerHTML;
Or substitute your conditional of choice.
Create a variable that counts the number of elements with that particular class, then create an if statement.
For example:
var chosenClass = document.querySelectorAll('.chosen-single').length;
if(chosenClass == 0) {
null;
}
else {
}

Cannot do "split" in chrome's console

I am trying to get links from one page. Here's a simple code to get all links from certain dom element.
var $ = jQuery;
var page = $("#main .entry p");
var rez = [];
for(var i=0; i<page.length;i++) {
var title = $(page[i]).find("a").text();
var info = $(page[i]).text();
var page_url = $(page[i]).find("a").attr("href");
rez.push({
title: title,
page_url: page_url,
info: info
});
}
I am using this code in Chrome browser's console.
Everything works ok. rez array is populated, and I can veryfy it by something like console.table(rez).
Now I am trying to strip certain part from urls collected in previous step by using split
for(var i=0; i<rez.length;i++) {
console.log(rez[i].page_url); // <- this works
console.log(rez[i].page_url.split("http://something...")[1] ); // <- this fails
}
Important note! I am doing it all in one step by copying entire code (rez populating code and rez iterating in order to make split).
And I am getting this error in console:
VM7064:18 Uncaught TypeError: Cannot read property 'split' of undefined
at <anonymous>:18:29
Why??
The split() function is used to split a string into an array of substrings. In split function as parameter you have to put a separator for example:
"http://something...like-this.com/blablabla".split("/");
This will return you an array ["http:", "", "something...like-this.com", "blablabla"]
In your case you try to split by some text "http://something..." and to get the second element of the array [1]. This will return you undefined in all your cases.

Cannot access second field in a 2 dimension array in javascript

I have a 2 dimension array defined as
var thischart = [[],[]];
and the array contains the following data created programatically:
1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10,0,11,0,12,0,13,24,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0
I cannot get the single value of the second field in the particular array cell. For example, if I use the following command to get the value:
alert("thischart[i,1]=" + thischart[0, 1]);
I get the following answer:
thischart[i,1]=2,0
I tried using the second dimension to access the data as
thischart[0][1]);
but it gives me an error message:
I just want to get the second single value in the array such as for array cell 13 I want the value 24 from above. Does anyone have an answer on how to access this array?
I populated the array as follows and then updated it thru program logic:
$hours = [];
for($i = 0; $i< 24; $i++){
$hours[$i] = [];
$hours[$i][0] = ($i + 1);
$hours[$i][1] = "0";
}
And the answer to this question is below:
for(var i in thischart){
var tc = thischart[i];
myvalue = tc[1]); // this is the value I want
}
Thanks to everyone who responded.
For all of them like this:
for(var i in thischart){
var tc = thischart[i];
for(var n in tc){
// n is internal index
// tc[n] is internal value
}
}
For a single value from the first internal Array, the second value:
thischart[0][1];
Why don't you use the console to see what's the return of
thischart[0];
Because it should contain an array. If it does, then
thischart[0][1];
is perfectly valid syntax. And if it doesn't, then
thischart[0,1]
means nothing whatsoever.
Do something like this:
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]); // 1
do you mean something like this:...
http://jsfiddle.net/DSrcz/1/
var arr = [1,0,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0];
arr[33]=1000;
alert(arr[13]);
alert(arr[33]);

got stuck with this set of code in jquery validate

var formRules = $(this).data('rules');
var formValues = $(this).data('values');
if(formRules || formValues){
var rulesArray = formRules.split(',');
var valuesArray = formValues.split(',');
for(var i=0; i < rulesArray.length; i++){
//alert(rulesArray[i]);
$.validationEngine.defaults.rulesArray[i] = valuesArray[i];
}
}
else{
return false;
}
This throws an error like following
Error: TypeError: $.validationEngine.defaults.rulesArray is undefined
Source File: http://localhost:8380/javascript/jquery.validationEngine.js
Line: 2092
I cannot find the problem with this code.Any help is welcome
EDIT:
I am trying to set the global options eg:scroll using the for loop.
The formRules string will have these options comma seperated and the corresponding values in the formValues string.
So i am expecting it to come like $.validationEngine.defaults.scroll = true;
change this line
$.validationEngine.defaults.rulesArray[i] = valuesArray[i];
to this
$.validationEngine.defaults[rulesArray[i]] = valuesArray[i];
rulesArray is not a child of $.validationEngine.defaults. The values stored in your rulesArray are. The syntax in my second code block references everything properly.
This is called Bracket Notation, a way to get an object's property using any sort of valid calculation (like rulesArray[i], or "myStringPropertyName"). see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators for other methods.

Categories