moses toh moses toh - 6 months ago 13
Javascript Question

How to check undefined variable 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?

Answer

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