472

Typically if we just use alert(object); it will show as [object Object]. How to print all the content parameters of an object in JavaScript?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
cometta
  • 35,071
  • 77
  • 215
  • 324

15 Answers15

802

This will give you very nice output with an indented JSON object using JSON.stringify:

alert(JSON.stringify(YOUR_OBJECT_HERE, null, 4));

The second argument (replacer) alters the contents of the string before returning it.

The third argument (space) specifies how many spaces to use as white space for readability.

JSON.stringify documentation here.

Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
Igor Jerosimić
  • 13,621
  • 6
  • 44
  • 53
  • 41
    +1 for cross-platform support. Standardized in ECMAScript 5th Edition, with support in Firefox 3.6, Chrome (ver?), Safari 4, and IE8. FYI: The 4 parameter is the number of spaces for each indention level. It may also be a string, e.g. "\t". The null parameter is a placeholder for a filtering function, if you want to limit what gets shown. See: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify – Noach Magedman Feb 26 '12 at 14:24
  • 3
    endlessly useful in the IE8 JS debugger. – Dead.Rabit Aug 14 '12 at 15:13
  • 22
    This doesn't work for objects with circular reference chains - Chrome gives an error: TypeError: Converting curcular structure to JSON – DavidJ May 15 '13 at 12:57
  • 9
    I'm seeing this same circular structure error in Chrome: `Uncaught TypeError: Converting circular structure to JSON`. Am I doing something wrong, or is this endemic to Chrome? – delliottg Jun 05 '13 at 22:54
  • 1
    Nice answer. You saved my day, I'm using this in Phonegap. – Jun Sep 05 '13 at 04:38
  • 1
    You may use https://www.npmjs.org/package/json-stringify-safe to avoid circular reference issues. – Toilal Sep 24 '14 at 07:28
329

If you are using Firefox, alert(object.toSource()) should suffice for simple debugging purposes.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lukman
  • 18,462
  • 6
  • 56
  • 66
  • 7
    Also supported in IE9 (if not earlier), but not by Chrome 17 or Safari 5. – Noach Magedman Feb 26 '12 at 14:26
  • 12
    Is there a cross-browser way of doing something similar? – Anderson Green Oct 02 '12 at 01:30
  • 62
    In recent browsers, you can use `console.dir(object)` to dump the contents of an object to the debugging console (F12 on most browsers). – rossipedia Jul 07 '13 at 15:40
  • 10
    I was trying to use this in console.log(object.toSource()); didn't work for me.. – maths Jun 06 '14 at 22:25
  • With firefox quantum 58, object.toSource() is slowing down the browser extremely. It might be my object (json string), but it shouldn't happen. EDIT: i'ts actually a cyclic object value. JSON.stringify() sends warning to console, which is better than the .toSource() behavior (no warning, semi-freezing) – Soleil Jan 31 '18 at 16:05
  • Best answer is the one that uses `console.dir(object)`, as it works for most modern browsers and takes care of cyclic references too. Plus 1 for the user who mentioned it. Thank you! – Binita Bharati Feb 13 '20 at 05:32
  • @BinitaBharati well, I answered this in 2009 when console.dir did not exist ... maybe in 2037, console.dir would no longer be the best .. – Lukman Mar 07 '20 at 07:56
79

Aside from using a debugger, you can also access all elements of an object using a foreach loop. The following printObject function should alert() your object showing all properties and respective values.

function printObject(o) {
  var out = '';
  for (var p in o) {
    out += p + ': ' + o[p] + '\n';
  }
  alert(out);
}

// now test it:
var myObject = {'something': 1, 'other thing': 2};
printObject(myObject);

Using a DOM inspection tool is preferable because it allows you to dig under the properties that are objects themselves. Firefox has FireBug but all other major browsers (IE, Chrome, Safari) also have debugging tools built-in that you should check.

Miguel Ventura
  • 10,344
  • 2
  • 31
  • 41
  • 6
    Might want to add if (o.hasOwnProperty(p)) inside the loop – Mike Blandford Oct 26 '09 at 15:00
  • 3
    That's a good idea, but when debugging I'd rather see it all. Perhaps even better would be something like: for (var p in o) { if (!o.hasOwnProperty(p)) out += '(inherited) '; out += p + ': ' + o[p] + '\n'; } – Miguel Ventura Oct 26 '09 at 15:27
33

If you just want to have a string representation of an object, you could use the JSON.stringify function, using a JSON library.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
17

You could Node's util.inspect(object) to print out object's structure.

It is especially helpful when your object has circular dependencies e.g.

$ node

var obj = {
   "name" : "John",
   "surname" : "Doe"
}
obj.self_ref = obj;

util = require("util");

var obj_str = util.inspect(obj);
console.log(obj_str);
// prints { name: 'John', surname: 'Doe', self_ref: [Circular] }

It that case JSON.stringify throws exception: TypeError: Converting circular structure to JSON

Michal
  • 611
  • 5
  • 11
14

Print content of object you can use

console.log(obj_str);

you can see the result in console like below.

Object {description: "test"} 

For open console press F12 in chrome browser, you will found console tab in debug mode.

Nikunj K.
  • 8,779
  • 4
  • 43
  • 53
8

You should consider using FireBug for JavaScript debugging. It will let you interactively inspect all of your variables, and even step through functions.

Jonathan Feinberg
  • 44,698
  • 7
  • 80
  • 103
7

Use dir(object). Or you can always download Firebug for Firefox (really helpful).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
OverLex
  • 2,501
  • 1
  • 24
  • 27
3

Javascript for all!

String.prototype.repeat = function(num) {
    if (num < 0) {
        return '';
    } else {
        return new Array(num + 1).join(this);
    }
};

function is_defined(x) {
    return typeof x !== 'undefined';
}

function is_object(x) {
    return Object.prototype.toString.call(x) === "[object Object]";
}

function is_array(x) {
    return Object.prototype.toString.call(x) === "[object Array]";
}

/**
 * Main.
 */
function xlog(v, label) {
    var tab = 0;

    var rt = function() {
        return '    '.repeat(tab);
    };

    // Log Fn
    var lg = function(x) {
        // Limit
        if (tab > 10) return '[...]';
        var r = '';
        if (!is_defined(x)) {
            r = '[VAR: UNDEFINED]';
        } else if (x === '') {
            r = '[VAR: EMPTY STRING]';
        } else if (is_array(x)) {
            r = '[\n';
            tab++;
            for (var k in x) {
                r += rt() + k + ' : ' + lg(x[k]) + ',\n';
            }
            tab--;
            r += rt() + ']';
        } else if (is_object(x)) {
            r = '{\n';
            tab++;
            for (var k in x) {
                r += rt() + k + ' : ' + lg(x[k]) + ',\n';
            }
            tab--;
            r += rt() + '}';
        } else {
            r = x;
        }
        return r;
    };

    // Space
    document.write('\n\n');

    // Log
    document.write('< ' + (is_defined(label) ? (label + ' ') : '') + Object.prototype.toString.call(v) + ' >\n' + lg(v));
};



// Demo //

var o = {
    'aaa' : 123,
    'bbb' : 'zzzz',
    'o' : {
        'obj1' : 'val1',
        'obj2' : 'val2',
        'obj3' : [1, 3, 5, 6],
        'obj4' : {
            'a' : 'aaaa',
            'b' : null
        }
    },
    'a' : [ 'asd', 123, false, true ],
    'func' : function() {
        alert('test');
    },
    'fff' : false,
    't' : true,
    'nnn' : null
};

xlog(o, 'Object'); // With label
xlog(o); // Without label

xlog(['asd', 'bbb', 123, true], 'ARRAY Title!');

var no_definido;
xlog(no_definido, 'Undefined!');

xlog(true);

xlog('', 'Empty String');
Eduardo Cuomo
  • 17,828
  • 6
  • 117
  • 94
2

You can also use Prototype's Object.inspect() method, which "Returns the debug-oriented string representation of the object".

http://api.prototypejs.org/language/Object/inspect/

JustinStolle
  • 4,182
  • 3
  • 37
  • 48
2

You can give your objects their own toString methods in their prototypes.

kennebec
  • 102,654
  • 32
  • 106
  • 127
2

Simple function to alert contents of an object or an array .
Call this function with an array or string or an object it alerts the contents.

Function

function print_r(printthis, returnoutput) {
    var output = '';

    if($.isArray(printthis) || typeof(printthis) == 'object') {
        for(var i in printthis) {
            output += i + ' : ' + print_r(printthis[i], true) + '\n';
        }
    }else {
        output += printthis;
    }
    if(returnoutput && returnoutput == true) {
        return output;
    }else {
        alert(output);
    }
}

Usage

var data = [1, 2, 3, 4];
print_r(data);
Rayiez
  • 1,420
  • 19
  • 20
2

You can use json.js from http://www.json.org/js.html to change json data to string data.

hay
  • 21
  • 1
0

Internet Explorer 8 has developer tools which is similar to Firebug for Firefox. Opera has Opera DragonFly, and Google Chrome also has something called Developer Tools (Shift+Ctrl+J).

Here is more a more detailed answer to debug JavaScript in IE6-8: Using the IE8 'Developer Tools' to debug earlier IE versions

Community
  • 1
  • 1
gregers
  • 12,523
  • 8
  • 46
  • 41
-6

I faced similar problem, The reason for it was i make use of ajax to fetch data. In this case i had made two asynchronous ajax call. In one i just return string msg and show in alert. In second ajax call i fetch arraylist in json format and decode it in js. So my second request use to process first and i was getting alert of object.

So just check. 1. alert should contain string. 2. If u get arrayList or any other Object decode it.

All the best!