0

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.

3 Answers 3

2

You could use in to check:

if (item in values && 'total' in values[item]) {
    console.log('defined');
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

+1 for actually explaining what happens. And providing code based on the OP's.
1

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

7 Comments

this code throws: Uncought TypeError: Cannot read property 'total' of undefined
@kriss.andrejevs make sure you are passing string "220" to a item and not a number 220
@Murali you pass the if only if the object is not defined. You need to check for !==.
@Murali Just that your logging output now should say "defined", because that's what you're testing for.
I think you have kind of missed the problem and suggested a fix that isn't required... although you have addressed the issue after the above comments, it still feels a bit "off course"
|

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.