104

In JavaScript / jQuery, if I alert some object, I get either [object] or [object Object]

Is there any way to know:

  1. what is the difference between these two objects

  2. what type of Object is this

  3. what all properties does this object contains and values of each property

?

2

7 Answers 7

153

You can look up an object's keys and values by either invoking JavaScript's native for in loop:

var obj = {
    foo:    'bar',
    base:   'ball'
};

for(var key in obj) {
    alert('key: ' + key + '\n' + 'value: ' + obj[key]);
}

or using jQuery's .each() method:

$.each(obj, function(key, element) {
    alert('key: ' + key + '\n' + 'value: ' + element);
});

With the exception of six primitive types, everything in ECMA-/JavaScript is an object. Arrays; functions; everything is an object. Even most of those primitives are actually also objects with a limited selection of methods. They are cast into objects under the hood, when required. To know the base class name, you may invoke the Object.prototype.toString method on an object, like this:

alert(Object.prototype.toString.call([]));

The above will output [object Array].

There are several other class names, like [object Object], [object Function], [object Date], [object String], [object Number], [object Array], and [object Regex].

5
  • 31
    "Everything is an object", that's not true, and it is one of the big misconceptions in the language. There are what we call primitive types: Number, String, Boolean, Undefined and Null. They can be often confused with the primitive wrappers, objects created with built-in constructors, e.g.: typeof new String("foo"); produces "object", it is a wrapped primitive value, while typeof "foo"; produces "string". See also Nov 2, 2010 at 16:03
  • I agree with CMS and once you run into the difference between a primitive string and the String object, you'll realize your capabilities ~ especially when trying to minimize code.
    – vol7ron
    Nov 2, 2010 at 16:11
  • 7
    @CMS That's not quite true, either. The "primitive" string is an object in its own right; it just has a different selection of methods. Likewise with numbers and booleans. However, Undefined and Null are primitives without methods.
    – Izkata
    Jan 17, 2013 at 21:41
  • @Izkata not true. var str = 'primitive'; str.foo = 'bar'; /*wouldn't work*/ whereas var oStr = new String('string object'); oStr.foo = 'bar'; /*works*/ If you're going to abstract it and call them all objects, then you can get away with thinking of primitives as primitive objects, but it's not equivalent to the superclass of true JavaScript objects.
    – vol7ron
    Apr 9, 2015 at 3:28
  • simply use console.log to inspect objects
    – john Smith
    Jul 5, 2017 at 19:03
13

To get listing of object properties/values:

  1. In Firefox - Firebug:

    console.dir(<object>);
    
  2. Standard JS to get object keys borrowed from Slashnick:

       var fGetKeys = function(obj){
          var keys = [];
          for(var key in obj){
             keys.push(key);
          }
          return keys;
       }
    
    // Example to call it:
    
       var arrKeys = fGetKeys(document);
    
       for (var i=0, n=arrKeys.length; i<n; i++){
          console.log(i+1 + " - " + arrKeys[i] + document[arrKeys[i]] + "\n");
       }
    

Edits:

  1. <object> in the above is to be replaced with the variable reference to the object.
  2. console.log() is to be used in the console, if you're unsure what that is, you can replace it with an alert()
7

i) what is the difference between these two objects

The simple answer is that [object] indicates a host object that has no internal class. A host object is an object that is not part of the ECMAScript implementation you're working with, but is provided by the host as an extension. The DOM is a common example of host objects, although in most newer implementations DOM objects inherit from the native Object and have internal class names (such as HTMLElement, Window, etc). IE's proprietary ActiveXObject is another example of a host object.

[object] is most commonly seen when alerting DOM objects in Internet Explorer 7 and lower, since they are host objects that have no internal class name.

ii) what type of Object is this

You can get the "type" (internal class) of object using Object.prototype.toString. The specification requires that it always returns a string in the format [object [[Class]]], where [[Class]] is the internal class name such as Object, Array, Date, RegExp, etc. You can apply this method to any object (including host objects), using

Object.prototype.toString.apply(obj);

Many isArray implementations use this technique to discover whether an object is actually an array (although it's not as robust in IE as it is in other browsers).


iii) what all properties does this object contains and values of each property

In ECMAScript 3, you can iterate over enumerable properties using a for...in loop. Note that most built-in properties are non-enumerable. The same is true of some host objects. In ECMAScript 5, you can get an array containing the names of all non-inherited properties using Object.getOwnPropertyNames(obj). This array will contain non-enumerable and enumerable property names.

0
4

I hope this doesn't count as spam. I humbly ended up writing a function after endless debug sessions: http://github.com/halilim/Javascript-Simple-Object-Inspect

function simpleObjInspect(oObj, key, tabLvl)
{
    key = key || "";
    tabLvl = tabLvl || 1;
    var tabs = "";
    for(var i = 1; i < tabLvl; i++){
        tabs += "\t";
    }
    var keyTypeStr = " (" + typeof key + ")";
    if (tabLvl == 1) {
        keyTypeStr = "(self)";
    }
    var s = tabs + key + keyTypeStr + " : ";
    if (typeof oObj == "object" && oObj !== null) {
        s += typeof oObj + "\n";
        for (var k in oObj) {
            if (oObj.hasOwnProperty(k)) {
                s += simpleObjInspect(oObj[k], k, tabLvl + 1);
            }
        }
    } else {
        s += "" + oObj + " (" + typeof oObj + ") \n";
    }
    return s;
}

Usage

alert(simpleObjInspect(anyObject));

or

console.log(simpleObjInspect(anyObject));
2

Get FireBug for Mozilla Firefox.

use console.log(obj);

2
  • 1
    I fail to see how your firebug is any different from mine, but I'd use dir instead of log to list the object
    – vol7ron
    Nov 2, 2010 at 16:17
  • console.log is just as effective, you can click on the object in the log to get the "dir" anyway...
    – gnarf
    Nov 2, 2010 at 17:21
1

Spotlight.js is a great library for iterating over the window object and other host objects looking for certain things.

// find all "length" properties
spotlight.byName('length');

// or find all "map" properties on jQuery
spotlight.byName('map', { 'object': jQuery, 'path': '$' });

// or all properties with `RegExp` values
spotlight.byKind('RegExp');

// or all properties containing "oo" in their name
spotlight.custom(function(value, key) { return key.indexOf('oo') > -1; });

You'll like it for this.

0

Scanning object for first intance of a determinated prop:

var obj = {a:'Saludos',
            b:{b_1:{b_1_1:'Como estas?',b_1_2:'Un gusto conocerte'}},
           d:'Hasta luego'
            }
function scan (element,list){
    var res;
    if (typeof(list) != 'undefined'){
        if (typeof(list) == 'object'){
            for(key in list){
               if (typeof(res) == 'undefined'){
                res = (key == element)?list[key]:scan(element,list[key]);
               }
            });
        }
    }
    return res;
}
console.log(scan('a',obj));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.