ChatGPT解决这个技术问题 Extra ChatGPT

How can I display a JavaScript object?

How do I display the content of a JavaScript object in a string format like when we alert a variable?

The same formatted way I want to display an object.

Would you please reword your question? What do you mean by "formatted way"? As in, with rich formatting, like bold/italic/etc?
is there a way to display the runtime value of a variable by printing the value of the variable using some console commands?
@BlackPanther Just do console.log("", yourObject1, yourObject2, yourObject3, etc...);. A shorter version is to just do console.log(yourObject1, yourObject2, etc...);.
Can you please select a better answer that more accurately reflects community consensus?
Some tips: You can use colors to have a better view of: console.log('%c Sample Text', 'color:green;'); Or add some VAR in the text using: console.log(`Sample ${variable}`, 'color:green;');

u
user229044

Use native JSON.stringify method. Works with nested objects and all major browsers support this method.

str = JSON.stringify(obj);
str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.
console.log(str); // Logs output to dev tools console.
alert(str); // Displays output using window.alert()

Link to Mozilla API Reference and other examples.

obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)

Use a custom JSON.stringify replacer if you encounter this Javascript error

"Uncaught TypeError: Converting circular structure to JSON"

For more readable output try JSON.stringify(obj, null, 4). This'll write it out as neatly indented text
JSON.stringify can only show a small subset of javascript values, and will throw an exception for the rest - console.log does not have this problem.
If you are a newbie like me, don't forget console.log i.e. console.log(JSON.stringify(obj,null, 4));
"Uncaught TypeError: Converting circular structure to JSON" when ob=window.
I had cases where it did not work : it showed {} for a non-empty object. So be sure to check with console.log(obj) before thinking your object is empty when strigify() returns {}.
A
Audwin Oyong

If you want to print the object for debugging purposes, use the code:

var obj = {
  prop1: 'prop1Value',
  prop2: 'prop2Value',
  child: {
    childProp1: 'childProp1Value',
  },
}
console.log(obj)

will display:

https://i.stack.imgur.com/x0Tvz.png

Note: you must only log the object. For example, this won't work:

console.log('My object : ' + obj)

Note ': You can also use a comma in the log method, then the first line of the output will be the string and after that, the object will be rendered:

console.log('My object: ', obj);

That function also works on Google Chrome when using the JavaScript Console (Shift+Control+J or Shift+Control+I, depending on the Chrome version). Also note that console.log(obj1, obj2) works very nicely, too, so you don't have to call console.log() for every object when logging multiple variables. Also, always remember to remove all such calls in production, as it will break browsers that do not implement it (such as Internet Explorer).
Yes it prints [object Object] but it has a little expando-toggly button beside it that lets you inspect the contents of the object.
@hughes it actually can do both. i have an object i created with: var obj = { "foo" : false }; and another object that is being passed into a callback from a server, the one passed through the callback prints with the little arrow so you can open it up, the statically created one just prints [object Object] with no arrow. I'm trying to figure this out too, any other thoughts?
console.log("id:"+obj); won't output correctly as it outputs a string as you see it there, you need to specify it like this: console.log("id:"); console.log(obj);
Try console.log(JSON.stringify(obj)) or console.dir(obj)
B
Ben McCann
var output = '';
for (var property in object) {
  output += property + ': ' + object[property]+'; ';
}
alert(output);

This is what exactly i want. I am using google maps v3 and the directionrenderer returns an object. That has four items and in that one objects name keeps changing so we need to find that. For that this method really helped. Besides this way we can get all the names of the properties and objects. Or is there any other way to find the names of the objects and properties?
+1, not all javascript is run in browsers or can be debugged in them.
You probably want to mask out the built in cruft with hasOwnProperty most of the time.
Omg -- 0: [; 1: o; 2: b; 3: j; 4: e; 5: c; 6: t; 7: ; 8: O; 9: b; 10: j; 11: e; 12: c; 13: t; 14: ];
A little late finding this, but as it got requested on my birthday last year (29th aug), here is a working fiddle. jsfiddle.net/MrMarlow/fq53o6o9
R
Rob Bednark

console.dir(object):

Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.

Note that the console.dir() feature is non-standard. See MDN Web Docs


Yes this is a good solution, however it only works as exptected if you want to log only the object (e.g. console.dir(obj)). In case you want to concatenate a sting to the output, it'll give you [object Object].
A massive advantage of console.dir is that you can still expand and read the values in your console after the variable has been garbage collected. This is described in another SO article here
And one more advantage of console.dir is that when you save console to file, all properties are in file as expected. That doesn't happen when using console.log only.
A
Abhishek Goel

try this :

console.log(JSON.stringify(obj))

This will print the stringify version of object. So instead of [object] as an output you will get the content of object.


typeerror: Converting circular structure to JSON?
@KaidenPrince see this answer for your error: stackoverflow.com/questions/4816099/… It is likely a DOM element in your object. If that's the case, you're best attempting to just log to the console in chrome or firefox and inspect there. Otherwise you'd have to strip out all circular elements before the JSON.stringify is called in order for it to work.
Solution is to simply split into 2 separate commands believe it or not: console.log("id:"); console.log(obj);
JSON.stringify does not understand Map
r
rink.attendant.6

Well, Firefox (thanks to @Bojangles for detailed information) has Object.toSource() method which prints objects as JSON and function(){}.

That's enough for most debugging purposes, I guess.


Object.toSource() doesn't seem to work for Chrome, is this expected? Or does Chrome not fall under "advanced browsers"? =)
Old thread, just found it through Google. .toSource() is actually Firefox only. Just thought I'd let you know.
G
Garry

If you want to use alert, to print your object, you can do this:

alert("myObject is " + myObject.toSource());

It should print each property and its corresponding value in string format.


toSource() doesn't work in non-gecko browsers (e.g. Chrome, Safari)
V
Vlad Bezden

If you would like to see data in tabular format you can use

console.table(obj);

Table can be sorted if you click on the table column.

You can also select what columns to show:

console.table(obj, ['firstName', 'lastName']);

You can find more information about console.table here


w
wilsonpage

Function:

var print = function(o){
    var str='';

    for(var p in o){
        if(typeof o[p] == 'string'){
            str+= p + ': ' + o[p]+'; </br>';
        }else{
            str+= p + ': { </br>' + print(o[p]) + '}';
        }
    }

    return str;
}

Usage:

var myObject = {
    name: 'Wilson Page',
    contact: {
        email: 'wilson@hotmail.com',
        tel: '123456789'
    }  
}

$('body').append( print(myObject) );

Example:

http://jsfiddle.net/WilsonPage/6eqMn/


Print method call the browser to print the page to pdf :p
@jsh you should turn the if-else around and check for object instead of only string. updated fiddle: jsfiddle.net/6eqMn/594
@wilsonpage This is failing if I add integer value to tel property :(
A
Aliaksandr Sushkevich

In NodeJS you can print an object by using util.inspect(obj). Be sure to state the depth or you'll only have a shallow print of the object.


R
Raza Rafaideen

Simply use

JSON.stringify(obj)

Example

var args_string = JSON.stringify(obj);
console.log(args_string);

Or

alert(args_string);

Also, note in javascript functions are considered as objects.

As an extra note :

Actually you can assign new property like this and access it console.log or display it in alert

foo.moo = "stackoverflow";
console.log(foo.moo);
alert(foo.moo);

The question itself states: "Like when we 'alert' a variable", so that's not really an answer. And also your other option "JSON.stringify(obj)" has already been mentioned in "Nov 27 2010", you're only cluttering this question with duplicates and non-answers. Your point about assigning new properties is also senseless in this context.
M
Max Alexander Hanna

NB: In these examples, yourObj defines the object you want to examine.

First off my least favorite yet most utilized way of displaying an object:

This is the defacto way of showing the contents of an object

console.log(yourObj)

https://i.stack.imgur.com/Bxak7.png

I think the best solution is to look through the Objects Keys, and then through the Objects Values if you really want to see what the object holds...

console.log(Object.keys(yourObj));
console.log(Object.values(yourObj));

https://i.stack.imgur.com/aFpJc.png

There is also this new option if you're using ECMAScript 2016 or newer:

Object.keys(yourObj).forEach(e => console.log(`key=${e}  value=${yourObj[e]}`));

https://i.stack.imgur.com/cz4DR.png

Next up :

console.table(yourObj)

https://i.stack.imgur.com/qPYhu.png


Would you expand the example to include Object and obj.
not sure I understand the comment, but I added differing names for objects that should have a name. object was not explicit enough.
console.table(yourObj) worked for me on Google Chrome Version 77.0.3865.90 (Official Build) (64-bit). Thanks for sharing!
j
jpoppe

To print the full object with Node.js with colors as a bonus:

console.dir(object, {depth: null, colors: true})

Colors are of course optional, 'depth: null' will print the full object.

The options don't seem to be supported in browsers.

References:

https://developer.mozilla.org/en-US/docs/Web/API/Console/dir

https://nodejs.org/api/console.html#console_console_dir_obj_options


W
Walter Caraza

Use this:

console.log('print object: ' + JSON.stringify(session));

y
yonia

As it was said before best and most simply way i found was

var getPrintObject=function(object)
{
    return JSON.stringify(object);
}

This is the easiest and fastest solution, however it doesn't work on big objects such as navigator.
A
Anton Harniakou

Here's a way to do it:

console.log("%o", obj);

Interesting. Is there any more information on this?
In the context of Chrome-dev-tool, google did mentioned this in this link. referring to the section "String substitution and formatting"
I saw it in mdn docs.
So underrated answer, this is exactly what I was looking for.
I routinely use the following as a debug statement. console.log("id-str %o",{obj1:obj1,obj2:obj2,...}); The debug window identifies each object and I can drill down on those that are interesting.
P
Pimp Trizkit

(This has been added to my library at GitHub)

Reinventing the wheel here! None of these solutions worked for my situation. So, I quickly doctored up wilsonpage's answer. This one is not for printing to screen (via console, or textfield or whatever). It does work fine in those situations and works just fine as the OP requested, for alert. Many answers here do not address using alert as the OP requested. Anyhow, It is, however, formatted for data transport. This version seems to return a very similar result as toSource(). I've not tested against JSON.stringify, but I assume this is about the same thing. This version is more like a poly-fil so that you can use it in any environment. The result of this function is a valid Javascript object declaration.

I wouldn't doubt if something like this was already on SO somewhere, but it was just shorter to make it than to spend a while searching past answers. And since this question was my top hit on google when I started searching about this; I figured putting it here might help others.

Anyhow, the result from this function will be a string representation of your object, even if your object has embedded objects and arrays, and even if those objects or arrays have even further embedded objects and arrays. (I heard you like to drink? So, I pimped your car with a cooler. And then, I pimped your cooler with a cooler. So, your cooler can drink, while your being cool.)

Arrays are stored with [] instead of {} and thus dont have key/value pairs, just values. Like regular arrays. Therefore, they get created like arrays do.

Also, all string (including key names) are quoted, this is not necessary unless those strings have special characters (like a space or a slash). But, I didn't feel like detecting this just to remove some quotes that would otherwise still work fine.

This resulting string can then be used with eval or just dumping it into a var thru string manipulation. Thus, re-creating your object again, from text.

function ObjToSource(o){
    if (!o) return 'null';
    var k="",na=typeof(o.length)=="undefined"?1:0,str="";
    for(var p in o){
        if (na) k = "'"+p+ "':";
        if (typeof o[p] == "string") str += k + "'" + o[p]+"',";
        else if (typeof o[p] == "object") str += k + ObjToSource(o[p])+",";
        else str += k + o[p] + ",";
    }
    if (na) return "{"+str.slice(0,-1)+"}";
    else return "["+str.slice(0,-1)+"]";
}

Let me know if I messed it all up, works fine in my testing. Also, the only way I could think of to detect type array was to check for the presence of length. Because Javascript really stores arrays as objects, I cant actually check for type array (there is no such type!). If anyone else knows a better way, I would love to hear it. Because, if your object also has a property named length then this function will mistakenly treat it as an array.

EDIT: Added check for null valued objects. Thanks Brock Adams

EDIT: Below is the fixed function to be able to print infinitely recursive objects. This does not print the same as toSource from FF because toSource will print the infinite recursion one time, where as, this function will kill it immediately. This function runs slower than the one above, so I'm adding it here instead of editing the above function, as its only needed if you plan to pass objects that link back to themselves, somewhere.

const ObjToSource=(o)=> {
    if (!o) return null;
    let str="",na=0,k,p;
    if (typeof(o) == "object") {
        if (!ObjToSource.check) ObjToSource.check = new Array();
        for (k=ObjToSource.check.length;na<k;na++) if (ObjToSource.check[na]==o) return '{}';
        ObjToSource.check.push(o);
    }
    k="",na=typeof(o.length)=="undefined"?1:0;
    for(p in o){
        if (na) k = "'"+p+"':";
        if (typeof o[p] == "string") str += k+"'"+o[p]+"',";
        else if (typeof o[p] == "object") str += k+ObjToSource(o[p])+",";
        else str += k+o[p]+",";
    }
    if (typeof(o) == "object") ObjToSource.check.pop();
    if (na) return "{"+str.slice(0,-1)+"}";
    else return "["+str.slice(0,-1)+"]";
}

Test:

var test1 = new Object();
test1.foo = 1;
test1.bar = 2;

var testobject = new Object();
testobject.run = 1;
testobject.fast = null;
testobject.loop = testobject;
testobject.dup = test1;

console.log(ObjToSource(testobject));
console.log(testobject.toSource());

Result:

{'run':1,'fast':null,'loop':{},'dup':{'foo':1,'bar':2}}
({run:1, fast:null, loop:{run:1, fast:null, loop:{}, dup:{foo:1, bar:2}}, dup:{foo:1, bar:2}})

NOTE: Trying to print document.body is a terrible example. For one, FF just prints an empty object string when using toSource. And when using the function above, FF crashes on SecurityError: The operation is insecure.. And Chrome will crash on Uncaught RangeError: Maximum call stack size exceeded. Clearly, document.body was not meant to be converted to string. Because its either too large, or against security policy to access certain properties. Unless, I messed something up here, do tell!


Crash prone. Try ObjToSource(document.body), for example.
ok, I found the issue. I was not checking for null valued objects. That is fixed now. But, you still cant do ObjToSource(document.body) because of infinite recursion. Even document.body.toSource() in FireFox returns an empty object.
@BrockAdams - There now its fixed for infinite recursion, however document.body is still not printable. See NOTE.
document.body was just a shortcut to pointing out some big problems. You've now fixed the worst of those and I already upvoted. (Although, I do believe that a different approach could handle document.body. Most of the answers here would not do well against it either.)
Well, if you (or anyone else) got any ideas of how to get past the fact that such a large object will fill up the stack during recursion or bypass security restrictions. I would love to hear it. Thanks for the vote!
s
sreepurna

If you would like to print the object of its full length, can use

console.log(require('util').inspect(obj, {showHidden: false, depth: null})

If you want to print the object by converting it to the string then

console.log(JSON.stringify(obj));


you would need to add the JSON.stringify when you try to concatenate with a string object. If you use console.log(object), it should pretty print the contents of the object
m
mmaclaurin

I needed a way to recursively print the object, which pagewil's answer provided (Thanks!). I updated it a little bit to include a way to print up to a certain level, and to add spacing so that it is properly indented based on the current level that we are in so that it is more readable.

// Recursive print of object
var print = function( o, maxLevel, level ) {
    if ( typeof level == "undefined" ) {
        level = 0;
    }
    if ( typeof level == "undefined" ) {
        maxLevel = 0;
    }

    var str = '';
    // Remove this if you don't want the pre tag, but make sure to remove
    // the close pre tag on the bottom as well
    if ( level == 0 ) {
        str = '<pre>';
    }

    var levelStr = '';
    for ( var x = 0; x < level; x++ ) {
        levelStr += '    ';
    }

    if ( maxLevel != 0 && level >= maxLevel ) {
        str += levelStr + '...</br>';
        return str;
    }

    for ( var p in o ) {
        if ( typeof o[p] == 'string' ) {
            str += levelStr +
                p + ': ' + o[p] + ' </br>';
        } else {
            str += levelStr +
                p + ': { </br>' + print( o[p], maxLevel, level + 1 ) + levelStr + '}</br>';
        }
    }

    // Remove this if you don't want the pre tag, but make sure to remove
    // the open pre tag on the top as well
    if ( level == 0 ) {
        str += '</pre>';
    }
    return str;
};

Usage:

var pagewilsObject = {
    name: 'Wilson Page',
    contact: {
        email: 'wilson@hotmail.com',
        tel: '123456789'
    }  
}

// Recursive of whole object
$('body').append( print(pagewilsObject) ); 

// Recursive of myObject up to 1 level, will only show name 
// and that there is a contact object
$('body').append( print(pagewilsObject, 1) ); 

R
Ritu

You can also use ES6 template literal concept to display the content of a JavaScript object in a string format.

alert(`${JSON.stringify(obj)}`);

const obj = { "name" : "John Doe", "habbits": "Nothing", }; alert(`${JSON.stringify(obj)}`);


n
nils petersohn

I always use console.log("object will be: ", obj, obj1). this way I don't need to do the workaround with stringify with JSON. All the properties of the object will be expanded nicely.


S
Socrates

Another way of displaying objects within the console is with JSON.stringify. Checkout the below example:

var gandalf = {
  "real name": "Gandalf",
  "age (est)": 11000,
  "race": "Maia",
  "haveRetirementPlan": true,
  "aliases": [
    "Greyhame",
    "Stormcrow",
    "Mithrandir",
    "Gandalf the Grey",
    "Gandalf the White"
  ]
};
//to console log object, we cannot use console.log("Object gandalf: " + gandalf);
console.log("Object gandalf: ");
//this will show object gandalf ONLY in Google Chrome NOT in IE
console.log(gandalf);
//this will show object gandalf IN ALL BROWSERS!
console.log(JSON.stringify(gandalf));
//this will show object gandalf IN ALL BROWSERS! with beautiful indent
console.log(JSON.stringify(gandalf, null, 4));

M
Mukesh Chapagain

Javascript Function

<script type="text/javascript">
    function print_r(theObj){ 
       if(theObj.constructor == Array || theObj.constructor == Object){ 
          document.write("<ul>") 
          for(var p in theObj){ 
             if(theObj[p].constructor == Array || theObj[p].constructor == Object){ 
                document.write("<li>["+p+"] => "+typeof(theObj)+"</li>"); 
                document.write("<ul>") 
                print_r(theObj[p]); 
                document.write("</ul>") 
             } else { 
                document.write("<li>["+p+"] => "+theObj[p]+"</li>"); 
             } 
          } 
          document.write("</ul>") 
       } 
    } 
</script>

Printing Object

<script type="text/javascript">
print_r(JAVACRIPT_ARRAY_OR_OBJECT);
</script> 

via print_r in Javascript


I'm not sure if this is a bug in the js.do example I'm using, but this only seems to output the first full "branch" of the tree. ie it follows the first reference of the first reference... ad infinitum
u
user3632930
var list = function(object) {
   for(var key in object) {
     console.log(key);
   }
}

where object is your object

or you can use this in chrome dev tools, "console" tab:

console.log(object);


I think your answer is incomplete. (not me that cause downvote) This, yet, only print the key..
thanks for your answer, it has inspired me to do this: console.log(Object.keys(object)); while I know that only prints the properties keys, it is enough to me for my purposes ;)
k
karlzafiris

Assume object obj = {0:'John', 1:'Foo', 2:'Bar'}

Print object's content

for (var i in obj){
    console.log(obj[i], i);
}

Console output (Chrome DevTools) :

John 0
Foo 1
Bar 2

Hope that helps!


A
Alireza

I prefer using console.table for getting clear object format, so imagine you have this object:

const obj = {name: 'Alireza', family: 'Dezfoolian', gender: 'male', netWorth: "$0"};

https://i.stack.imgur.com/31MFN.png


R
Rafael Xavier

If you're looking for an inliner for Node.js...

console.log("%o", object);

G
George Kagan

A little helper function I always use in my projects for simple, speedy debugging via the console. Inspiration taken from Laravel.

/**
 * @param variable mixed  The var to log to the console
 * @param varName string  Optional, will appear as a label before the var
 */
function dd(variable, varName) {
    var varNameOutput;

    varName = varName || '';
    varNameOutput = varName ? varName + ':' : '';

    console.warn(varNameOutput, variable, ' (' + (typeof variable) + ')');
}

Usage

https://i.stack.imgur.com/EZRQG.png

var obj = {field1: 'xyz', field2: 2016};
dd(obj, 'My Cool Obj'); 

https://i.stack.imgur.com/EcNAs.png


S
Scott

The console.log() does a great job of debugging objects, but if you are looking to print the object to the page content, here's the simplest way that I've come up with to mimic the functionality of PHP's print_r(). A lot these other answers want to reinvent the wheel, but between JavaScript's JSON.stringify() and HTML's

 tag, you get exactly what you are looking for.
                			                   			

var obj = { name: 'The Name', contact: { email: 'thename@gmail.com', tel: '123456789' }}; $('body').append('

'+JSON.stringify(obj, null, 4)+'
');


b
bitless

i used pagewil's print method, and it worked very nicely.

here is my slightly extended version with (sloppy) indents and distinct prop/ob delimiters:

var print = function(obj, delp, delo, ind){
    delp = delp!=null ? delp : "\t"; // property delimeter
    delo = delo!=null ? delo : "\n"; // object delimeter
    ind = ind!=null ? ind : " "; // indent; ind+ind geometric addition not great for deep objects
    var str='';

    for(var prop in obj){
        if(typeof obj[prop] == 'string' || typeof obj[prop] == 'number'){
          var q = typeof obj[prop] == 'string' ? "" : ""; // make this "'" to quote strings
          str += ind + prop + ': ' + q + obj[prop] + q + '; ' + delp;
        }else{
          str += ind + prop + ': {'+ delp + print(obj[prop],delp,delo,ind+ind) + ind + '}' + delo;
        }
    }
    return str;
};

It is very sloppy.