Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript : testing object property length

Tags:

javascript

I have some objects with properties. I wanted to test to see if they had characters in them so I initially wrote this:

if (MyObject.Prop1.length > 0) {....}

However, sometimes the object may not have a certain property so I was getting the error "cannot get length".

I changed it by writing this:

if (MyObject.Prop1 && MyObject.Prop1.length > 0) {....}

I'm using the chrome inspector and when I run the code, I don't get the error anymore. Is this going to work in every browser?

Thanks.

like image 873
frenchie Avatar asked Apr 26 '26 19:04

frenchie


2 Answers

As an alternative:

if ('Prop1' in MyObject && MyObject.Prop1.length > 0) { ... )

Or, to be even more careful:

if (MyObject.hasOwnProperty('Prop1') && MyObject.Prop1.length > 0) { ... }

Of course that might be the wrong thing to do, depending on the nature of "MyObject".

like image 191
Pointy Avatar answered Apr 29 '26 11:04

Pointy


Yes it will work quite fine, although you can save yourself the > 0 and just do

if (MyObject.Prop1 && MyObject.Prop1.length) {....}

since anything other than zero will evaluate to true.

like image 25
Martin Jespersen Avatar answered Apr 29 '26 11:04

Martin Jespersen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!