1

I have an array of JSON strings. Consider the first element of the array has 4 attributes, {a:name,b:address,c:dob,d:country},

and the second element has only 3 attributes, it has no 'c' attribute. when iterating through the array, if the attribute is not present, i should set it to a default value. I used,(let 'c' be 'rating')

if(!results.hasOwnProperty('rating'))
  results.rating = 1;

It works fine for elements that have 'rating' attribute. But for elements that dont have rating attribute, i get an error saying, 'Cannot find 'rating''.

Is there any other way to find whether the attribute is present or not?

balajiboss
  • 932
  • 2
  • 12
  • 20
  • That should *not* generate an error .. `"captain".hasOwnProperty("tightpants")` evaluates to false. Have a *full* test-case demonstrating the "Cannot find '..'" error? –  Jul 12 '12 at 04:21
  • 1
    Have a look at this question for cross browser solution. http://stackoverflow.com/questions/135448/how-do-i-check-to-see-if-an-object-has-an-attribute-in-javascript – Subir Kumar Sao Jul 12 '12 at 04:26
  • @subirkumarsao Very nice complete answer given there but .. on which browser [of any concern] does `hasOwnProperty` *not* work? It is defined in ECMAScript 3rd Edition and even IE6 supports it .. –  Jul 12 '12 at 04:28
  • Mentioned in the answer: All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.) – Subir Kumar Sao Jul 12 '12 at 04:30

0 Answers0