0

I am trying to use Youtube's Gdata JSON response in javascript. My code iterates through the playlist and extract the item data.but for few videos the rating is not there which throws

"TypeError: item.gd$rating is undefined"

is there a way to check before accessing the element.

this is the code with with i fetch the json response.

    var avgrating = item['gd$rating']['average'];
    var maxrating = item['gd$rating']['max'];
    var minrating = item['gd$rating']['min'];
    var numRaters = item['gd$rating']['numRaters'];

1 Answer 1

3

One way you can just do to avoid error is

var rating = item['gd$rating'] || {}; // If it is undefined default it to empty object
var avgrating = rating['average']; //now if it is not present it will just give undefoned as value
var maxrating = irating['max'];
var minrating = rating['min'];
var numRaters = rating['numRaters'];

Or explicitly check:

  var rating = item['gd$rating'], avgrating, maxrating;
  if(rating) 
  {
       avgrating = rating['average'];
       maxrating  =rating['max'];
       ... 
  }

Note that in the if condition we are checking for truthiness of the expression so, anything other than undefined, null, "", false, 0 will be treated as true and will go into the condition. But here you are sure that it will be either an object or nothing so you can rely on this check.

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

Comments

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.