1

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?

2
  • you have error here if(priceObject.DayPrice.Rate). Commented May 14, 2016 at 11:06
  • 1
    if (priceObject.DayPrice && priceObject.DayPrice.Rate).. Commented May 14, 2016 at 11:06

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

I need you help. Look here : stackoverflow.com/questions/38280802/…
@mosestoh I haven't worked on amcharts. Not sure if I will be able to help.
No problem. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.