kriss.andrejevs
kriss.andrejevs

Reputation: 21

Check if JSON object is defined

I have a JSON object

var values = {"220":{"287":19,"total":19},"":{"240":76,"total":76},"total":95};

and I'm not able to check if values[item]['total'] is defined.

item is variable got from selectbox value, basically I'm trying to make if else statement, I need to check if values[item]['total'] is defined, I have 2 scenarios

  1. item is 220, or another number which goes in "" (json object is generated with php, in this case it has 220 and "", because it doesnt have "color" value, only size, but usally it have correct values)

  2. and in my case item value is the one in {} brackets - for example 287 and 240

This code :

if ( typeof values[item]['total'] === 'undefined' ) {
    console.log('undefined');
}

throws: Uncaught TypeError: Cannot read property 'total' of undefined.

Upvotes: 0

Views: 4672

Answers (3)

Murali Murugesan
Murali Murugesan

Reputation: 22619

What about using hasOwnProperty()

 if ( typeof values[item]!== 'undefined' && 
      values[item].hasOwnProperty('total')===false ) 
     { 
        console.log('Total undefined'); 
     }

Note: Make sure you are passing a string for item. so it will be compiled as item["220"] and not item[220]. In JavaScript object indexers are accessed by string names

Upvotes: 1

musefan
musefan

Reputation: 48455

That error will be caused when the value of item does not match any of the properties it will return null, and then you try to access a property of it but you can't because the item is null.

What you should do is check both parts for undefined:

if ( typeof values[item] === 'undefined' || typeof values[item]['total'] === 'undefined') {
    console.log('undefined');
}

Here is a working example

Upvotes: 2

xdazz
xdazz

Reputation: 160963

You could use in to check:

if (item in values && 'total' in values[item]) {
    console.log('defined');
}

Upvotes: 2

Related Questions