How to determine if a javascript object is simple or complex?
Asked Answered
G

7

8

Basically I need to tell apart the following two:

var simple = 5 // or "word", or 56.78, or any other "simple" object
var complex = {propname: "propvalue", "otherprop": "othervalue"}
Gagarin answered 19/9, 2011 at 22:24 Comment(1)
Your "simple object" is not Object at all, it is called primitive.Methane
H
14

Using typeof operator you can determine the following:

"number"        Operand is a number
"string"        Operand is a string
"boolean"       Operand is a Boolean
"object"        Operand is an object
"undefined"     Operand is not defined.

Edited: As it was suggested in a comment you may want to also check if value is null, as typeof null will return object.

Hovel answered 19/9, 2011 at 22:26 Comment(2)
Believe it or not, typeof null is 'object'. Crockford has a field day with this...Fluff
An array is also an object according to typeof typeof [] === "object"Elwandaelwee
S
6

You could use typeof:

typeof 5 == "number";
typeof 1.5 == "number";
typeof true == "boolean";
typeof "word" == "string";
typeof {} == "object";

Basically:

if(obj == null) {
  //null or undefined
}
else if(typeof obj == "object") {
  //It's "complex"
}
else {
  //Primitive or "simple"
}

Note: null will return "object", so you need to check for it.

Sporadic answered 19/9, 2011 at 22:26 Comment(0)
P
2

The problem is that more than just {} returns a type of 'object'

typeof 5 == 'number'
typeof NaN == 'number'
typeof 'test' == 'string'
typeof true == 'boolean'
typeof undefined == 'undefined'    

typeof null == 'object'
typeof /asdf/ == 'object' // this is true in some engines, like Firefox's. Not in V8 (in which it is 'function')
typeof [] == 'object'
typeof {} == 'object'

But, by using toString you can check further:

toString.call(null) == '[object Window]' // or '[object global]' or '[object Null]' - depends on engine
toString.call(/asdf/) == '[object RegExp]'
toString.call([]) == '[object Array]'
toString.call({}) == '[object Object]'

So, the best way to check is:

var test;

test = {};
typeof test == 'object' && toString.call(test) == '[object Object]'; // true

test = [];
typeof test == 'object' && toString.call(test) == '[object Object]'; // false

// et cetera

Hope that helps

Primarily answered 19/9, 2011 at 22:43 Comment(0)
H
1

Credit here

Object.prototype.getName = function() { 
   var funcNameRegex = /function (.{1,})\(/;
   var results = (funcNameRegex).exec((this).constructor.toString());
   return (results && results.length > 1) ? results[1] : "";
};


var simple  = 5;            // or "word", or 56.78, or any other "simple" object
var complex = { propname    : "propvalue"
              , "otherprop" : "othervalue"
              };

simple.getName();           // returns: "Number"
complex.getName();          // returns: "Object"
Haunted answered 19/9, 2011 at 22:32 Comment(0)
B
0

Try the following

if (typeof obj === 'object') {
  // It's complex
} else {
  // It's not
}
Bradeord answered 19/9, 2011 at 22:26 Comment(0)
C
0

In your case:

var simple = 5; // number, not an object
var simple = new Number(5); // now it is an object, but still the value is 5
var complex = {propname: "propvalue", "otherprop": "othervalue"};

for ( property in complex ) {
   if ( complex.hasOwnProperty( property ) )
   {
      alert ( 'composite object' );
      return;
   } else {
      alert ( 'simple object' );
      return;
   }
}

As of what I understand from you question - you need to tell if the object has properties/methods.

Commiserate answered 19/9, 2011 at 22:36 Comment(0)
P
-1

You could just make a simple function that returns true for simple types:

function isSimple( a ) {
    return (typeof a).match(/(number)|(boolean)|(string)/)
}

Note that this will return true for NaN as it's considered a number, and false for 'undefined' - but you could easily modify this to suit your specific case.

Run the snippet below to see it in action

<script>
// return true/false if typeof matches simple regex pattern
function isSimple( a ) {
    return (typeof a).match(/(number)|(boolean)|(string)/);
}

// setup some tests cases
var tests = [
  [1,2,3],
  'hello',
  7,
  { foo: 'bar' },
  NaN
]

// log output of isSimple function against each test case
for( var i in tests ) {
  var value = tests[ i ];
  if( isSimple( value ) ) {
    console.log( 'simple value', value );
  } else {
    console.log( 'not simple', value );
  }
}
  
  
</script>
Polemoniaceous answered 19/10, 2016 at 8:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.