Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if a Javascript object is a "complex" object or just a string

I want to be able to pass either a string literal,

'this is a string'

or a javascript object,

{one: 'this', two: 'is', three: 'a', four: 'string' }

as argument to a function, and take different actions depending on whether it's a string or an object. How do I determine which is true?

To be specific, I want to iterate over the properties of an object, and do some parsing if a property is a string, but nest recursively if the property is an object. I've figured out how to use $.each() to iterate over the properties of the object, but if I just do this with the string, it treates the string as an array of letters rather than as a single thing. Can I get around this some other way?

like image 697
Tomas Aschan Avatar asked Jul 22 '10 10:07

Tomas Aschan


2 Answers

var data = {
    foo: "I'm a string literal",
    bar:  {
       content: "I'm within an object"
    }        
};

jQuery

$.each(data, function(i, element){
    if($.isPlainObject(element){
       // we got an object here
    }
});

There are similar methods like $.isArray() or $.isFunction() within the jQuery lib.

Native Javascript

for(var element in data){
   if(toString.call(element) === '[object Object]'){
      // we got an object here
   }
}

To use the hack'ish way with toString has the advantage, that you can identify whether it is really an object and an array. Both, objects and arrays would return object by using typeof element.

Long story short, you cannot rely on the typeof operator to distinguish true objects and arrays. For that you need the toString.call(). If you just need to know whether it is any object or not, typeof is just fine.

like image 111
jAndy Avatar answered Sep 21 '22 13:09

jAndy


var a = 'this is a string';

console.log(typeof a);   // Displays: "string"

var b = {one: 'this', two: 'is', three: 'a', four: 'string' };

console.log(typeof b);   // Displays: "object"

Therefore:

if (typeof yourArgument === 'string') {
   // Do the string parsing
}
else if (typeof yourArgument === 'object') {
   // Do the property enumeration
}
else {
   // Throw exception
}

UPDATE:

Some further considerations:

  1. See @Andy E's comment below.

  2. typeof null returns "object" as well. The same applies to any other object, including arrays.

like image 45
Daniel Vassallo Avatar answered Sep 20 '22 13:09

Daniel Vassallo