Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Check if the contents of a variable are an object or not

I'm using Sugarcube.

Simple question that I can't seem to figure out: How do I take an object
<<set $foo = {
    bar : 0
}>>
and check if it is or is not an object:
<<if isObject($foo)>>
    /%Do stuff here%/
<</if>>

Comments

  • You can try to use either Javascript's typeof operator or instanceof operator but as you will quickly find out many things in Javascript are objects.
    eg. Arrays, Sets, Dates, etc...

    1. Using typeof
    <<set $var to {key: "value"}>>
    Value is <<if typeof $var === 'object'>>an object<<else>>not an object<</if>>
    
    <<set $var to [1,2,3]>>
    But an Array is also <<if typeof $var === 'object'>>an object<<else>>not an object<</if>>
    
    <<set $var to "Valye">>
    While a String is <<if typeof $var === 'object'>>an object<<else>>not an object<</if>>
    
    <<set $var to 1>>
    Or a Number is <<if typeof $var === 'object'>>an object<<else>>not an object<</if>>
    
    2. Using instanceof
    <<set $var to {key: "value"}>>
    Value is <<if $var instanceof Object>>an object<<else>>not an object<</if>>
    
    <<set $var to [1,2,3]>>
    But an Array is also <<if $var instanceof Object>>an object<<else>>not an object<</if>>
    
    <<set $var to "Valye">>
    While a String is <<if $var instanceof Object>>an object<<else>>not an object<</if>>
    
    <<set $var to 1>>
    Or a Number is <<if $var instanceof Object>>an object<<else>>not an object<</if>>
    
    3. You could event try checking the Prototype of the value using Javascript's isPrototypeOf fuction but again lots of things will result in a value of true.
    <<set $var to {key: "value"}>>
    Value is <<if Object.prototype.isPrototypeOf($var)>>an object<<else>>not an object<</if>>
    
    <<set $var to [1,2,3]>>
    But an Array is also <<if Object.prototype.isPrototypeOf($var)>>an object<<else>>not an object<</if>>
    
  • Thanks man, really useful post!
Sign In or Register to comment.