-5

I have object like this var o = $scope['reservation']['bookings'][bookingKey]['meals']

When I do

if (o.hasOwnProperty('checkedProperty') {

  // code

}

I have error Uncaught TypeError: Cannot read property 'hasOwnProperty' of undefined.

I try too:

if (o['checkedProperty']) {

  // code to do if my object 'o' has 'checkedProperty'

}

but I have error: Uncaught TypeError: Cannot read property '26' of undefined.

How can I do to check this property?

Peter_Fretter
  • 1,135
  • 12
  • 20
Jan Kowalski
  • 205
  • 2
  • 7
  • 14

1 Answers1

2

You can't check if a property exists on an object when you don't have an object in the first place.

Check if o actually is an object:

if (typeof o !== "undefined" && o.hasOwnProperty('checkedProperty')) {
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • This will also fail if `o` is `null`. As a general solution: `if (o != null && o.hasOwnProperty('checkedProperty')) {` This assumes `o` has been declared. Otherwise: `if (typeof o !== 'undefined' && o !== null && o.hasOwnProperty('checkedProperty')) {` – Ray Nicholus Sep 27 '16 at 14:01