Print content of JavaScript object?

JavascriptObject

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

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.

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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.

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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');

Solution 10 - Javascript

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/

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Solution 13 - Javascript

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);

Solution 14 - Javascript

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: https://stackoverflow.com/questions/780059/using-the-ie8-developer-tools-to-debug-earlier-ie-versions/801547#801547

Solution 15 - Javascript

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncomettaView Question on Stackoverflow
Solution 1 - JavascriptIgor JerosimićView Answer on Stackoverflow
Solution 2 - JavascriptLukmanView Answer on Stackoverflow
Solution 3 - JavascriptMiguel VenturaView Answer on Stackoverflow
Solution 4 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 5 - JavascriptMichalView Answer on Stackoverflow
Solution 6 - JavascriptNikunj K.View Answer on Stackoverflow
Solution 7 - JavascriptJonathan FeinbergView Answer on Stackoverflow
Solution 8 - JavascriptOverLexView Answer on Stackoverflow
Solution 9 - JavascriptEduardo CuomoView Answer on Stackoverflow
Solution 10 - JavascriptcnpfmView Answer on Stackoverflow
Solution 11 - JavascriptkennebecView Answer on Stackoverflow
Solution 12 - JavascripthayView Answer on Stackoverflow
Solution 13 - JavascriptRayiezView Answer on Stackoverflow
Solution 14 - JavascriptgregersView Answer on Stackoverflow
Solution 15 - Javascriptuser3308542View Answer on Stackoverflow